Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How vue use getter setter on v-model?

Tags:

vue.js

vuejs2

<div id="app">
  <input v-model="msg"/>
  <p>{{ msg }}</p>
</div>

<script>
class A{

}
A.a = 1
new Vue({
  el: '#app',
  data: {
  },
  computed: {
    msg: {
      cache: false,
      set: function(val){
            A.a = val
      },
      get: function(){
        return A.a   
      }
    }
  }
})
</script>

run on jsfiddle

How vue use getter setter on v-model? I tried use getter and setter on v-model, but it didn't work.

like image 683
cyhone Avatar asked Oct 17 '22 12:10

cyhone


1 Answers

Your getters and setters are fine as is. (They're not strictly necessary in this example, since they're not doing anything to modify the user input, but I assume that's a simplification for the purposes of your question.)

There are two separate issues with your code:

  1. the input field is outside the Vue root node, so the framework can't see it. [You corrected this in a late edit to the question.]
  2. You're defining your data (A.a) outside of Vue, so the framework doesn't know to watch it for changes.

For the framework to be reactive to changes you must put the variable A in the data block of the component (and, if you really need an external variable, copy the updated value into it using the setter function).

new Vue({
  el: '#app',
  data: {
    A: { a: 1 } // <-- your external variable, moved to where Vue can see it
  },
  computed: {
    msg: {
      set: function(val) {
        this.A.a = val;
        // If necessary, also copy val into an external variable here
      },
      get: function() {
        return this.A.a
      }
    }
  }
})
<script src="https://unpkg.com/vue"></script>
<div id="app">
  <input v-model="msg" />
  <p>{{ msg }}</p>
</div>
like image 110
Daniel Beck Avatar answered Oct 21 '22 02:10

Daniel Beck