我正在尝试制作一个类似于 Medium 的文本编辑器。我正在使用内容可编辑的段落标签并将每个项目存储在一个数组中,并使用 v-for 渲染每个项目。但是,我在使用 v-model 将文本与数组绑定时遇到了问题。似乎与 v-model 和 contenteditable 属性有冲突。这是我的代码:
<div id="editbar">
<button class="toolbar" v-on:click.prevent="stylize('bold')">Bold</button>
</div>
<div v-for="(value, index) in content">
<p v-bind:id="'content-'+index" v-bind:ref="'content-'+index" v-model="content[index].value" v-on:keyup="emit_content($event)" v-on:keyup.delete="remove_content(index)" contenteditable></p>
</div>
在我的脚本中:
export default {
data() {
return {
content: [{ value: ''}]
}
},
methods: {
stylize(style) {
document.execCommand(style, false, null);
},
remove_content(index) {
if(this.content.length > 1 && this.content[index].value.length == 0) {
this.content.splice(index, 1);
}
}
}
}
我没有在网上找到任何答案。
原文由 Soubriquet 发布,翻译遵循 CC BY-SA 4.0 许可协议
我昨天想通了!确定了这个解决方案。我基本上只是手动跟踪我的
content
数组中的 innerHTML,方法是更新任何可能的事件并通过手动分配具有动态引用的相应元素重新渲染,例如content-0
,content-1
,… 工作精美: