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

本文介绍了如何在Vue2.x中自定义组件上使用v-model指令进行双向数据绑定。通过示例代码展示了一个简单的计数器组件,展示了如何通过$emit('input')触发父组件的更新,以及如何避免使用@input事件监听,直接利用v-model实现数据同步。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

我们都知道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来进行父子组件传值,可以省略自己再去定义一个事件去接收子集传的值




评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值