030 V 自定义事件之v-model
本帖最后由 不二如是 于 2018-10-24 17:07 编辑https://xxx.ilovefishc.com/forum/201808/24/170823gj1tj61c4apj6o1e.jpg
上一讲我们通过原生Vue实现了自定义事件,本次学习通过v-model实现。
从Vue 2.x开始可以在自定义组件上使用v-model指令,稍微修改一下上一讲的代码:
<div id="myApp">
<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);
}
}
});
var app = new Vue({
el:"#myApp",
data:{
total:0
}
})
</script>
仍然是单击按钮,增加1的效果,不过这次组件$emit()的事件名是特殊的“input”。
在使用组件的父级,并没有在<my-component>上使用@input="handler",而是直接用了v-model绑定的一个数据total。
v-model还可以用来创建自定义的表单输入组件,进行双向数据绑定,例如:
<div id="myApp">
<p>总数:{{total}}</p>
<my-component v-model="total"></my-component>
<button @click="handleReduce">-1</button>
</div>
<script>
Vue.component('my-component',{
props:['value'],
template:'<input :value="value" @input="updateValue">',
methods:{
updateValue:function (event) {
this.$emit('input',event.target.value);
}
}
});
var app = new Vue({
el:"#myApp",
data:{
total:0
},
methods:{
handleReduce:function () {
this.total--;
}
}
})
</script>
实现这样一个具有双向绑定的v-model组件要满足下面两个要求:
1、接受一个value属性
2、在有新的value时出发input事件
课后作业
1、在Vue 2.x中不可以在自定义组件中使用v-model指令(T/F)
2、补充?处代码:
Vue.?('my-component',{
template:'<button @click="handleClick">+1</button>',
data:function () {
return{
counter:0
}
},
methods:{
handleClick:function(){
this.counter++;
this.$?('input',this.counter);
}
}
});
3、实现可以双向绑定的v-model需要满足哪两个条件?
答案:
**** Hidden Message *****
如果有收获,别忘了评分{:10_281:} :
http://xxx.fishc.com/forum/201709/19/094516hku92k2g4kefz8ms.gif
这位鱼油,如果喜欢Vue,请订阅 专辑(传送门)(不喜欢更要订阅{:10_297:} )
http://xxx.fishc.com/forum/201803/21/151715umqz1qoywp11wjbq.gif 1.F
2.component emit
3.接受一个value属性
在有新的value时出发input事件 1.F
2.
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);
}
}
});
3.接受一个value属性;在有新的value时触发input事件 0 1
页:
[1]