vuejs 2.4 two way data binding


<script type="text/javascript" src="https://unpkg.com/vue@2.4.4/dist/vue.js"></script>
  
<div id="app">
  input counter:<input type="text" v-model="input_counter">
  <button @click="changeProp">change counter prop to {{input_counter}}</button>
  <button-counter :counter.sync="main_counter" ></button-counter>
</div>


Vue.component('button-counter', {
  template: `
  <div>
  <p>{{getCounter}}</p>
  <button v-on:click="incrementCounter">counter + 1</button>
  <button v-on:click="decrementCounter">counter - 1</button>
  </div>
  `,
  props: ['counter'],
  data: function () {
    return {

      //copy prop to inner variable
      c_counter:this.counter
    }
  },
  watch: { 
        //watch prop counter changed
        counter: function(newVal, oldVal) {
          this.c_counter = parseInt(newVal)
        }
      },
  computed: {
    getCounter: function() {
      return  "counter:" + this.c_counter
    }
  },
  
  methods: {
    incrementCounter: function () {
      this.c_counter += 1

      //update prop
      this.$emit('update:counter', this.c_counter)
    },
    decrementCounter: function () {
      this.c_counter -= 1

      //update prop
      this.$emit('update:counter', this.c_counter)
    }
  },
})

new Vue({
  el: '#app',
  data: {
    main_counter:'waiting for init',
    input_counter:100
  },
  created: function(){
      this.initCounter()
  },
  methods: {

    initCounter:function(){
      //maybe counter come from remote
      var vm = this
      setTimeout(function(){
          vm.main_counter = 0    
      },1000)
    },
    changeProp: function(){
      this.main_counter = this.input_counter
    }

  }
})


demo on jsfiddle

demo on jsfiddle

留言