版权声明: https://blog.csdn.net/m_oman/article/details/80410730
在组件上使用v-model
来自官网上的解释:
自定义事件可以用于创建支持v-model的自定义输入组件。
但是首先我们得记住之前的v-model的解释,也就是
<input v-model="searchText">
等价于
<custominput
v-bind:value="searchText"
v-on:input="searchText=$event">
</custominput>
为了能够使它正常工作,这个组件内的<input>必须:1、将其value特性绑定到一个名为value的prop上; 2
在其input事件被出发的时候,将新的值通过自定义的input时间抛出!
故要写出如下代码:
Vue.component('custom-input',{
props:['value'],
template:`
<input v-bind:value="value"
v-on:input="$emit('input',$event.target.value)">
`
})
现在v-model就可以在组件上完美地工作起来
<custom-inpu v-model="searchText"></custome-input>
下面来一个朋友应用的例子:
自定义组件sidebar,要实现
<sidebar v-model="active"></sidebar>
父组件满足条件:data里面要有active元素
子组件满足条件:1、类似于父子单向传参,子组件中要有props名为value
2、类似于子父传参,(在子组件中设置active数据(只是个人用)),在子组件中进行监听
参数传入: value(val) {
if(val) {
this.active = val console.log("val") console.log(val) } }, 参数传出: active(val) { this.$emit('input', val) }
嘻嘻嘻可以在正常使用啦,以后再用还会进行其他优化