以前咱们学过用 v-model
进行双向数据绑定:css
<div id="root"> <textarea class="textarea" v-model="comment"></textarea> </div> <script> var vm = new Vue({ el:"#root", data:{ comment:"这是一条评论" } }); </script>
并且,提到过,v-model
只能用于表单控件,若是用于其余元素,好比 p
:html
<p contenteditable="true" v-model="comment"></p>
那么就会报错:vue
v-model is not supported on this element type. If you are working with contenteditable, it's recommended to wrap a library dedicated for that purpose inside a custom component.ajax
它会提示用 custom component
,即自定义组件。在使用自定义组件以前,先来看看 v-model
的另一种等价写法:ide
<textarea :value="comment" @input="comment = $event.target.value"></textarea>
该过程很好理解,首先,动态绑定输入控件的 value
属性到 comment
变量上,而后对 input
事件进行监控,实时同步 comment
的值。this
若是用这种写法,就能够对 p
等元素进行双向绑定了。因为 p
元素没有 value
属性,能够使用 v-text
或者插值:spa
<p contenteditable="true" @input="comment = $event.target.innerText">{{ comment }}</p>
或者:双向绑定
<p contenteditable="true" v-text="comment" @input="comment = $event.target.innerText"></p>
如今,咱们对评论的内容进行过滤,效果以下:code
能够使用自定义组件,好比:component
<comment v-model="comment"></comment>
如何让组件的 v-model
生效呢?须要按照 Vue 的约定:
接受一个 value
属性
在有新的 value
时触发 input
事件
跟咱们以前的写法相似:
Vue.component('comment',{ props:['value'], template:` <textarea :value="value" @input="filterComment($event.target.value)"></textarea> `, methods: { filterComment(comment){ this.$emit('input',comment) } } });
这样就能够实现简单的双向绑定了,并且咱们能够在 filterComment
方法中定义过滤规则:
filterComment(comment){ var filterRst = (comment.indexOf('敏感词') >= 0 ? comment.replace(\敏感词\g,"河蟹") : comment); this.$emit('input',filterRst) }
完整示例:
<!DOCTYPE html> <html lang="zh-cn"> <head> <meta charset="UTF-8"> <title>Document</title> <script src="https://cdn.bootcss.com/vue/2.2.6/vue.js"></script> <link rel="stylesheet" type="text/css" href="https://cdnjs.cloudflare.com/ajax/libs/bulma/0.4.1/css/bulma.css"> </head> <body> <div id="root" class="container"> <comment v-model="comment"></comment> </div> <script> Vue.component('comment',{ props:['value'], template:` <textarea class="textarea" :value="value" @input="filterComment($event.target.value)"></textarea> `, data(){ return { sensitiveList:['包子','蛤蛤'], replaceWord:'河蟹' } }, methods: { filterComment(comment){ var that = this; this.sensitiveList.forEach(function(word){ var regex = new RegExp(word,'g');; comment = (comment.indexOf(word) >= 0 ? comment.replace(regex,that.replaceWord) : comment); }) this.$emit('input',comment) } } }); var vm = new Vue({ el:"#root", data:{ comment:'这是一条评论' } }); </script> </body>