Vuetify - How to access data in form rule

冷暖自知 提交于 2019-12-12 10:50:51

问题


Can I access a data element in a rule?

Here is my code running

I'm trying to flip the value of a data element on a text field rule in a Vuetify form.

The rule itself works fine, however I'm unable to access the data element, I'm getting this error:

TypeError: Cannot set property 'disabled' of undefined

Here is my code:

data: function() {
return {
  disabled: false,
  rules:{
    sellerId(value){
      if(value.length == 0){
        this.disabled = true;
        return "What are you trying to do here?";  
      }
      else{
        return true;
      }
    }
  },

What am I doing wrong?


回答1:


rules are an array of functions, and if you need the function to be able to access data property, you can define them as component methods:

data: function () {
  return {
    disabled: false
  }
},
methods: { 
  sellerId (value) {
    if (value.length === 0) {
      this.disabled = true;
      return "What are you trying to do here?";  
    } else {
      return true;
    }
  }
}

And then in your Vuetify component:

<v-text-field :rules="[ sellerId ]"></v-text-field>



回答2:


While this isn't available to a rule function you can accomplish this by assigning the vue instance to a variable, which will bring it into scope by closure.

vm = new Vue({
    el: '#app',
    data: () => ({
        disabled: true,
        rules: [
            value => {
                if (value.length == 0) {
                    vm.disabled = true;
                    return "What are you trying to do here?";  
                }
                else {
                    return true;
                }
            }
        ],
'''



回答3:


try to define rules as computed property :

data: function() {
    return {
      disabled: false,
      ...
    }
  },
  computed: {
    sellerIdRules() {
      return [
         (v) => {
        if (value.length == 0) {
          this.disabled = true;
          return "What are you trying to do here?";
        } else {
          return true;
        } ]
      }
    }
  }


来源:https://stackoverflow.com/questions/53366501/vuetify-how-to-access-data-in-form-rule

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!