vue2.x自定义组件上使用v-model指令

来源:互联网 发布:设计公司logo软件 编辑:程序博客网 时间:2024/06/03 15:17

我们都知道v-model是双向数据绑定经常用到的指令,今天学习到在组件上使用v-model指令,感觉还挺不错的,分享一下

<div id="app">

<p>总数{{total}}</p>

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

</div>

<script>

Vue.component('my-component',{

template:'<button @click="handleClick">+1</button>',

data:function(){

return {

counter:0

}

},

methods:{

handleClick:function(){

this.counter++;

this.$emit('input',this.counter)

}

}

});

new Vue({

el:'#app',

data:{

total:0

}

})

</script>

运行上面代码,可以发现点击按钮是正常+1的效果,不过这次组件$emit()的事件名是特殊的input,在使用组件的父级,并没有在<my-component>上使用@input="handle",而是直接用了v-model绑定的一个数据total。

其实上面的示例大多数都是用自定义事件来实现,可以改写为

<div id="app">

<p>总数{{total}}</p>

<my-component @input="handle"></my-component>

</div>

<script>

Vue.component('my-component',{

template:'<button @click="handleClick">+1</button>',

data:function(){

return {

counter:0

}

},

methods:{

handleClick:function(){

this.counter++;

this.$emit('input',this.counter)

}

}

});

new Vue({

el:'#app',

data:{

total:0

},

methods:{

handle:function(sontotal){

//sontotal子集传过来的参数

this.total = sontotal

}

}

})

</script>

这篇写的目的是想说明,有些时候传值可以使用v-model来进行父子组件传值,可以省略自己再去定义一个事件去接收子集传的值