[转] vue 自定义组件使用v-model

 

v-model指令其实是下面的语法糖包装而成:

在一个组件上使用 v-model 时,会简化为:


因此,对于一个带有 v-model 的组件,它应该如下:

  • 接收一个 value prop
  • 触发 input 事件,并传入新值

利用 $emit 触发 input 事件:

this.$emit('input', value);

组件1:

复制代码
Vue.component('my-component', {
  template: `
`, computed:{ currentValue:function () { return this.value } }, props: ['value'], //接收一个 value prop methods: { handleInput(event) { var value = event.target.value; this.$emit('input', value); //触发 input 事件,并传入新值 } } });
复制代码
上面是将prop属性绑定到data里,以便修改 prop 数据(Vue不允许直接修改prop属性的值)#查看原理#

组件2:

复制代码
Vue.component("my-counter", {
  template: `

{{value}}

`, 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 事件,并传入新值 } } } });
复制代码

转载于:https://www.cnblogs.com/chris-oil/p/11417678.html

你可能感兴趣的:([转] vue 自定义组件使用v-model)