msg: {{msg}}...">
美文网首页
vue 自定义组件使用v-model

vue 自定义组件使用v-model

作者: 彬彬彬boboc | 来源:发表于2019-02-21 11:18 被阅读0次

<div id="app">

  <my-component v-model="msg"></my-component>

  msg: {{msg}}

  <my-counter v-model="num"></my-counter>

  num: {{num}}

</div>

Vue.component('my-component', {

  template: `<div>

  <input type="text" :value="currentValue" @input="handleInput"/>

  </div>`,

  computed:{

  currentValue:function () {

    return this.value

}

  },

  props: ['value'], //接收一个 value prop

  methods: {

    handleInput(event) {

      var value = event.target.value;

      this.$emit('input', value); //触发 input 事件,并传入新值

    }

  }

});

Vue.component("my-counter", {

  template: `<div>

  <h1>{{value}}</h1>

  <button @click="plus">+</button>

  <button @click="minu">-</button>

  </div>`,

  props: {

    value: Number //接收一个 value prop

  },

  data: function() {

    return {

      val: this.value

    }

  },

  methods: {

    plus() {

      this.val = this.val + 1

      this.$emit('input', this.val) //触发 input 事件,并传入新值

    },

    minu() {

      if(this.val>0){

        this.val = this.val-1

        this.$emit('input', this.val) //触发 input 事件,并传入新值

      }

    }

  }

});

new Vue({

el: '#app',

  data: {

  msg: 'hello world',

    num: 0

  }

})

相关文章

网友评论

      本文标题:vue 自定义组件使用v-model

      本文链接:https://www.haomeiwen.com/subject/jrcryqtx.html