vue—可编辑div的双向数据绑定,解决输入顺序错乱问题
新建子组件inputDiv.vue:
<template>
<div
class="sessionListBox_footer_input"
contenteditable="true"
ref="inpMsgRef"
v-text="msg"
@input="inputMsg"
@focus="isLocked = true"
@blur="isLocked = false"
>
</div>
</template>
<script>
export default {
data() {
return {
msg: this.value,
isLocked: false
}
},
props: {
value: {
type: String,
default: ''
}
},
methods: {
inputMsg() {
this.$emit('input', this.$el.innerHTML)
}
},
computed: {},
watch: {
value(n, o) {
if (!this.isLocked || !this.msg) {
this.msg = this.value
}
}
}
}
</script>
<style lang="less" scoped>
.sessionListBox_footer_input {
width: 99%;
height: 80%;
text-align: left;
padding-left: 1%;
outline: none;
}
</style>
父组件直接使用
```bash
<inputDiv v-model="inpMsg"></inputDiv>
以上内容借鉴于:[1(https://blog.youkuaiyun.com/weixin_38500689/article/details/103270928)
已经解决了双向绑定数据后造成光标一直在处于第一个字符前面,输入顺序错乱的问题(如输入12345,得到54321)。
就我本人使用,还遇到了一点小问题,我的输入框一开始是隐藏的,每次当我关闭输入框,重新打开的时候,输入的第一个字符光标依然不能正常移动(输入12345,得到23451)。在父组件使用的时候,把双向绑定的初始值由空字符串’’ ===>变成带一个空格的空字符串’ ’