<div contenteditable="true" v-model=""></div>
直接使用上面的代码会报错,因为'v-model' directives aren't supported on <div> elements.
参考网上各种解决办法,也未找到完美解决方案。
- 方法1 => https://segmentfault.com/a/1190000009225098
这个方法解决不了光标的问题,光标总是会置于文字前面,而且输入中文时也会有问题。
- 方法2 => https://segmentfault.com/a/1190000008261449
解决了光标的问题,但实际上数据是单项绑定的,innerText只更新了一次。
不能解决数据的有效双向绑定,只能通过其他方法达到效果,下面的方法算是勉强解决:
<template>
<div class="edit-div" ref="editor" :contenteditable="true" @input="changeText" @blur="editBlur"></div>
</template>
<script>
export default {
name: 'EditDiv',
props:{
isclear:'',
isfocus:false,
value: {
type: String,
default: ''
}
},
data () {
return {
}
},
watch: {
'isclear'(val){
if (val === 1) {
this.$refs.editor.innerHTML = ''
}
}
},
methods: {
changeText(){
this.$emit('input', this.$el.innerHTML)
},
editBlur(){
this.$refs.editor.focus()
if (!this.isfocus) {
this.$refs.editor.blur()
}
}
}
}
</script>
<!-- Add "scoped" attribute to limit CSS to this component only -->
<style scoped lang="scss">
.edit-div {
width:6rem;
min-height:.9rem;
max-height:2.3rem;
overflow-y:auto;
padding:0.2rem 0.2rem;
border-bottom: 0.01rem solid #e5e5e5;
box-sizing:border-box;
caret-color:#068708;
white-space: pre-wrap;
// &[contenteditable=true]{
// user-modify: read-write-plaintext-only;
// &:empty:before {
// content: attr(placeholder);
// display: block;
// color: #ccc;
// }
// }
&:focus{
outline:none;
border-bottom: 0.01rem solid #80af57;
}
}
</style>