前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >在自定义组件中使用v-model

在自定义组件中使用v-model

作者头像
大神带我来搬砖
发布2018-05-02 14:05:32
9960
发布2018-05-02 14:05:32
举报

遇到一个需求,关键词列表是用逗号分隔的字符串,最多三个关键词,为了在vue中对这个关键词列表进行编辑,可以将其定义为一个组件,组件中有3个input.用v-model将关键词列表绑定到组件上.input更新后产生input事件,更新列表值. 效果如图

组件代码如下

        Vue.component('my-component', {
            props : [ 'value' ],
            methods : {
                updateValue : function(){
                    this.$emit('input', this.tag1+","+this.tag2+","+this.tag3)
                }
            },
            watch:{
                tag1:function(){
                    this.updateValue()
                },
                tag2:function(){
                    this.updateValue()
                },
                tag3:function(){
                    this.updateValue()
                }
            },
            data : function(){
                return {
                    tag1:this.value.split(",")[0],
                    tag2:this.value.split(",")[1],
                    tag3:this.value.split(",")[2]
                    }
                },
            template : '<div> <input v-model="tag1"/> <input v-model="tag2"/> <input v-model="tag3"/></div>'
        })

调用组件时代码如下

    <div id="app">
        <div>message is {{message}}</div>
        <my-component v-model="message"></my-component>
    </div>

git地址https://github.com/kabike/vueComponent

本文参与 腾讯云自媒体分享计划,分享自作者个人站点/博客。
原始发表:2017.12.16 ,如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 作者个人站点/博客 前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体分享计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档