|
马上注册,结交更多好友,享用更多功能^_^
您需要 登录 才可以下载或查看,没有账号?立即注册
x
本帖最后由 不二如是 于 2018-10-24 17:07 编辑
上一讲我们通过原生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需要满足哪两个条件?
答案:
如果有收获,别忘了评分 :
这位鱼油,如果喜欢Vue,请订阅 专辑( 传送门)( 不喜欢更要订阅 )
|
|