功能效果图

功能描述
- input文本框,通过点击下方关键词,在文本框中插入该词
- 光标移动到文本之间,再点击下方关键词,在光标的位置插入该词
- 插入关键词后,文本框获取焦点,并将光标的位置定位到关键词后
代码实现
- 给
<el-input>
标签加上失去焦点事件 @blur="handleInputBlur"
- 获取光标位置
- 点击关键词时候,将文本内容从光标位置进行拆分,拼接关键词,设置焦点,处理光标位置
<template>
<div class="input-creative-word">
<el-input
ref="inputWord"
v-model="proxyValue"
class="input-item"
type="textarea"
:autosize="{minRows: 6}"
@blur="handleInputBlur"
/>
<div class="main-word">
<div class="main-word-left">
<span class="main-word-label">插入动态词包: </span>
<el-button
v-for="n in commonWordList"
:key="n.creativeWordId"
class="button-word"
type="text"
@click="btnClick(n.name)">+{{ n.name }}</el-button>
</div>
</div>
</div>
</template>
<script>
export default {
name: "InputCreativeWord",
data() {
return {
proxyValue:"",
commonWordList: [
{ name: "地点", creativeWordId: 1 },
{ name: "日期", creativeWordId: 2 },
{ name: "星期", creativeWordId: 3 },
{ name: "年龄", creativeWordId: 4 }
],
cursorIndex: "",
};
},
methods: {
handleInputBlur(e) {
this.cursorIndex = e.srcElement.selectionStart;
},
btnClick(label) {
const txt = this.proxyValue;
const start = txt.substring(0, this.cursorIndex);
const end = txt.substring(this.cursorIndex, txt.length);
this.proxyValue = start + `{${label}}` + end;
if (this.$refs.inputWord) {
this.$nextTick(() => {
var a = this.$refs.inputWord.$el.firstElementChild;
a.focus();
a.selectionStart = this.cursorIndex + label.length + 2;
a.selectionEnd = this.cursorIndex + label.length + 2;
});
}
}
}
};
</script>