vue div contenteditable属性,模拟v-model双向数据绑定功能
在一些特殊的请款下需要用div的contenteditable属性来模拟v-model的功能,但是直接在div上写v-model是不起作用的,首先来看一下v-model是怎么实现的:value="content" @input="content=$event.target.value" />直接把input上的方法移植到div上,会发现居然可以实现v-model的功能div c
·
在一些特殊的请款下需要用div的contenteditable属性来模拟v-model的功能,但是直接在div上写v-model是不起作用的,首先来看一下v-model是怎么实现的
<input :value="content" @input="content=$event.target.value" />
直接把input上的方法移植到div上,会发现居然可以实现v-model的功能
<div contenteditable="true" v-html="content" @input="content=$event.target.innerHTML"></div>
但是实际使用上有很多问题,比如光标的问题,我们可以依靠组件来对这些问题进行处理
<div id="app">
<m-contenteditable :child="content"></m-contenteditable>
<m-contenteditable :child="content"></m-contenteditable>
<div><pre v-html="content.txt"></pre></div>
</div>
<script>
Vue.component("mContenteditable",{
props:{
child:{
type:Object,
default:{
txt:""
}
}
},
data:function(){
return {
innerText:this.child.txt,
lock:false
}
},
watch:{
child:{
handler(newValue, oldValue) {
if(!this.lock) {
this.innerText=this.child.txt;
};
},
deep:true
}
},
methods:{
changeTxt:function(e){
this.child.txt=this.$el.innerHTML;
}
},
template:`<div class="box" contenteditable="true" v-html="innerText" @input="changeTxt" @focus="lock=true" @blur="lock=false"></div>`
});
new Vue({
el:"#app",
data:{
content:{
txt:"内容<img src=\"http://pub.idqqimg.com/lib/qqface/0.gif\" width=\"38\" height=\"38\">"
}
}
});
更多推荐
已为社区贡献5条内容
所有评论(0)