vue 自定义组件使用v-model

<input v-model="something">

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

<input
  :value="something"
  @:input="something = $event.target.value">

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

<custom-input
  :value="something"
  @input="value => { something = value }">
custom-input>

因此,对于一个带有 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://vuejs.org/v2/guide/components.html

转载于:https://www.cnblogs.com/bldf/p/6645225.html

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