javascript - After using the set method of a Vue.js calculated property, how can the value of the calculated property be updated accordingly?
天蓬老师
天蓬老师 2017-06-14 10:52:20
0
3
666

computed: {

cardNum: {
    get: function() {
        return this.ruleForm.cardNum;
    },
    set: function(val) {
        this.ruleForm.cardNum = val.substring(0, 20);
    }
}

}

I bound the cardNum to the v-model of the input, and wanted to use this to filter the value (it seems that you cannot bind filters to the variables of v-model after vue.js2.0), but I found that When more than 20 characters are entered, although this.ruleForm.cardNum will be intercepted, cardNum can exceed 20 characters. Could you please tell me how to implement this character length limit function?

天蓬老师
天蓬老师

欢迎选择我的课程,让我们一起见证您的进步~~

reply all(3)
習慣沉默

I think it’s mainly a matter of application scenarios and ideas.

  1. Application scenario: Generally, form verification is done when the focus is lost or when the user clicks the OK and save button, and then the corresponding copywriting prompt pops up. Just look for any registration page of any degree or Penguin. . If you restrict it like this, the interaction will not be friendly enough, and it will lead to deviations in your implementation ideas.

  2. Thinking: Regarding the understanding of computed and v-model, I do not recommend using them in this way. v-model itself is designed to achieve two-way binding, and using computed means writing one more set method and one more intermediate value.

If you really want to achieve it, you can try this

<input type="text" v-model="num">
data() {return { num: '' }}
watch: {
    num(a, b) {
        if (a.length > 20) { this.num = b }
    }

}
大家讲道理

I don’t know if this meets your needs

<input type="text" maxlength="20">
世界只因有你

If you do this, the setter of the calculated property will not be triggered unless triggered manually (vm)this.cardNum = 'what?'
View the documentation

Or you can directly use the watcher provided by vue, as follows:

watch: {
  'ruleForm.cardNum': function (newValue) {
     // do something...
  }
}

But it’s not recommended

Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template