我正在尝试制作一个类似于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);
}
}
}
}
我在网上没有找到任何答案。
我尝试了一个示例,eslint-plugin-vue报告说
v-model
在p
元素上不受支持。请参阅 valid-v-model 规则。
在撰写本文时,Vue 似乎并没有直接支持您想要的功能。我将提出两个通用解决方案:
<template>
<p
contenteditable
@input="onInput"
>
{{ content }}
</p>
</template>
<script>
export default {
data() {
return { content: 'hello world' };
},
methods: {
onInput(e) {
console.log(e.target.innerText);
},
},
};
</script>
可编辑.vue
<template>
<p
ref="editable"
contenteditable
v-on="listeners"
/>
</template>
<script>
export default {
props: {
value: {
type: String,
default: '',
},
},
computed: {
listeners() {
return { ...this.$listeners, input: this.onInput };
},
},
mounted() {
this.$refs.editable.innerText = this.value;
},
methods: {
onInput(e) {
this.$emit('input', e.target.innerText);
},
},
};
</script>
index.vue
<template>
<Editable v-model="content" />
</template>
<script>
import Editable from '~/components/Editable';
export default {
components: { Editable },
data() {
return { content: 'hello world' };
},
};
</script>
经过多次迭代,我发现对于您的用例,通过not使用单独的组件更容易获得可行的解决方案。看起来
contenteditable
元素非常棘手 - 尤其是在列表中呈现时。我发现在删除后我必须手动更新每个 innerText
的 p
才能使其正常工作。我还发现使用 ids 有效,但使用 refs 无效。
可能有一种方法可以在模型和内容之间获得完整的双向绑定,但我认为这需要在每次更改后操纵光标位置。
<template>
<div>
<p
v-for="(value, index) in content"
:id="`content-${index}`"
:key="index"
contenteditable
@input="event => onInput(event, index)"
@keyup.delete="onRemove(index)"
/>
</div>
</template>
<script>
export default {
data() {
return {
content: [
{ value: 'paragraph 1' },
{ value: 'paragraph 2' },
{ value: 'paragraph 3' },
],
};
},
mounted() {
this.updateAllContent();
},
methods: {
onInput(event, index) {
const value = event.target.innerText;
this.content[index].value = value;
},
onRemove(index) {
if (this.content.length > 1 && this.content[index].value.length === 0) {
this.$delete(this.content, index);
this.updateAllContent();
}
},
updateAllContent() {
this.content.forEach((c, index) => {
const el = document.getElementById(`content-${index}`);
el.innerText = c.value;
});
},
},
};
</script>
我想我可能想出了一个更简单的解决方案。请参阅下面的片段:
<!DOCTYPE html>
<html lang="en">
<head>
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/css/bootstrap.min.css">
</head>
<body>
<main id="app">
<div class="container-fluid">
<div class="row">
<div class="col-8 bg-light visual">
<span class="text-dark m-0" v-html="content"></span>
</div>
<div class="col-4 bg-dark form">
<button v-on:click="bold_text">Bold</button>
<span class="bg-light p-2" contenteditable @input="handleInput">Change me!</span>
</div>
</div>
</div>
</main>
<script src="https://cdn.jsdelivr.net/npm/vue"></script>
<script>
new Vue({
el: '#app',
data: {
content: 'Change me!',
},
methods: {
handleInput: function(e){
this.content = e.target.innerHTML
},
bold_text: function(){
document.execCommand('bold')
}
}
})
</script>
</body>
</html>
说明:
您可以编辑跨度,因为我添加了标签
contenteditable
。请注意,在 input
上,我将调用handleInput 函数,它将内容的innerHtml 设置为您插入到可编辑范围中的任何内容。然后,要添加粗体功能,您只需选择要加粗的内容并单击粗体按钮即可。
额外奖励!它也适用于 cmd+b ;)
希望这对某人有帮助!
快乐编码
请注意,我通过 CDN 引入了用于样式设置的 bootstrap css 和 vue,以便它可以在代码片段中运行。
您可以使用 watch 方法创建双向绑定 contentEditable。
Vue.component('contenteditable', {
template: `<p
contenteditable="true"
@input="update"
@focus="focus"
@blur="blur"
v-html="valueText"
@keyup.ctrl.delete="$emit('delete-row')"
></p>`,
props: {
value: {
type: String,
default: ''
},
},
data() {
return {
focusIn: false,
valueText: ''
}
},
computed: {
localValue: {
get: function() {
return this.value
},
set: function(newValue) {
this.$emit('update:value', newValue)
}
}
},
watch: {
localValue(newVal) {
if (!this.focusIn) {
this.valueText = newVal
}
}
},
created() {
this.valueText = this.value
},
methods: {
update(e) {
this.localValue = e.target.innerHTML
},
focus() {
this.focusIn = true
},
blur() {
this.focusIn = false
}
}
});
new Vue({
el: '#app',
data: {
len: 4,
val: "Test",
content: [{
"value": "<h1>Heading</h1><div><hr id=\"null\"></div>"
},
{
"value": "<span style=\"background-color: rgb(255, 255, 102);\">paragraph 1</span>"
},
{
"value": "<font color=\"#ff0000\">paragraph 2</font>"
},
{
"value": "<i><b>paragraph 3</b></i>"
},
{
"value": "<blockquote style=\"margin: 0 0 0 40px; border: none; padding: 0px;\"><b>paragraph 4</b></blockquote>"
}
]
},
methods: {
stylize: function(style, ui, value) {
var inui = false;
var ivalue = null;
if (arguments[1]) {
inui = ui;
}
if (arguments[2]) {
ivalue = value;
}
document.execCommand(style, inui, ivalue);
},
createLink: function() {
var link = prompt("Enter URL", "https://codepen.io");
document.execCommand('createLink', false, link);
},
deleteThisRow: function(index) {
this.content.splice(index, 1);
if (this.content[index]) {
this.$refs.con[index].$el.innerHTML = this.content[index].value;
}
},
add: function() {
++this.len;
this.content.push({
value: 'paragraph ' + this.len
});
},
}
});
<script src="https://unpkg.com/[email protected]/dist/vue.min.js"></script>
<div id="app">
<button class="toolbar" v-on:click.prevent="add()">ADD PARAGRAPH</button>
<button class="toolbar" v-on:click.prevent="stylize('bold')">BOLD</button>
<contenteditable ref="con" :key="index" v-on:delete-row="deleteThisRow(index)" v-for="(item, index) in content" :value.sync="item.value"></contenteditable>
<pre>
{{content}}
</pre>
</div>
您可以使用组件 v-model 在 Vue 中创建 contentEditable。
Vue.component('editable', {
template: `<p
v-bind:innerHTML.prop="value"
contentEditable="true"
@input="updateCode"
@keyup.ctrl.delete="$emit('delete-row')"
></p>`,
props: ['value'],
methods: {
updateCode: function($event) {
//below code is a hack to prevent updateDomProps
this.$vnode.child._vnode.data.domProps['innerHTML'] = $event.target.innerHTML;
this.$emit('input', $event.target.innerHTML);
}
}
});
new Vue({
el: '#app',
data: {
len: 3,
content: [{
value: 'paragraph 1'
},
{
value: 'paragraph 2'
},
{
value: 'paragraph 3'
},
]
},
methods: {
stylize: function(style, ui, value) {
var inui = false;
var ivalue = null;
if (arguments[1]) {
inui = ui;
}
if (arguments[2]) {
ivalue = value;
}
document.execCommand(style, inui, ivalue);
},
createLink: function() {
var link = prompt("Enter URL", "https://codepen.io");
document.execCommand('createLink', false, link);
},
deleteThisRow: function(index) {
this.content.splice(index, 1);
},
add: function() {
++this.len;
this.content.push({
value: 'paragraph ' + this.len
});
},
}
});
<script src="https://unpkg.com/[email protected]/dist/vue.min.js"></script>
<div id="app">
<button class="toolbar" v-on:click.prevent="add()">ADD PARAGRAPH</button>
<button class="toolbar" v-on:click.prevent="stylize('bold')">BOLD</button>
<editable v-for="(item, index) in content" :key="index" v-on:delete-row="deleteThisRow(index)" v-model="item.value"></editable>
<pre>
{{content}}
</pre>
</div>
我昨天就明白了!确定了这个解决方案。我基本上只是通过更新任何可能的事件来手动跟踪我的
content
数组中的innerHTML,并通过手动分配带有动态引用的相应元素来重新渲染,例如content-0
,content-1
,...效果很好:
<template>
<div id="editbar">
<button class="toolbar" v-on:click.prevent="stylize('bold')">Bold</button>
</div>
<div>
<div v-for="(value, index) in content">
<p v-bind:id="'content-'+index" class="content" v-bind:ref="'content-'+index" v-on:keydown.enter="prevent_nl($event)" v-on:keyup.enter="add_content(index)" v-on:keyup.delete="remove_content(index)" contenteditable></p>
</div>
</div>
</template>
<script>
export default {
data() {
return {
content: [{
html: ''
}]
}
},
methods: {
add_content(index) {
//append to array
},
remove_content(index) {
//first, check some edge conditions and remove from array
//then, update innerHTML of each element by ref
for(var i = 0; i < this.content.length; i++) {
this.$refs['content-'+i][0].innerHTML = this.content[i].html;
}
},
stylize(style){
document.execCommand(style, false, null);
for(var i = 0; i < this.content.length; i++) {
this.content[i].html = this.$refs['content-'+i][0].innerHTML;
}
}
}
}
</script>
我想我可能会做出贡献,因为我不认为给定的解决方案是最优雅或最简洁的,无法清楚地回答所需的内容,或者它们没有提供 Vue 的最佳使用。有些接近,但最终需要一些调整才能真正有效。 首先注意,
<p>
段落不支持v-model。内容位于 innerHTML 中,只能使用元素槽内的 {{content}}
添加。该内容在插入后不会被编辑。您可以为其提供初始内容,但每次刷新内容时,内容编辑光标都会重置到前面(不是自然的打字体验)。这导致了我的最终解决方案:
...
<p class="m-0 p-3" :contenteditable="manage" @input="handleInput">
{{ content }}
</p>
...
props: {
content: {type:String,defalut:"fill content"},
manage: { type: Boolean, default: false },
...
data: function() {
return {
bioContent: this.content
...
methods: {
handleInput: function(e) {
this.bioContent = e.target.innerHTML.replace(/(?:^(?: )+)|(?:(?: )+$)/g, '');
},
...
我的建议是,将初始静态内容值放入
<p>
插槽中,然后使用 @input
触发器来更新第二个 active 内容变量,其中包含从 contenteditable 操作放入innerHTML 的内容。您还需要修剪掉由 <p>
元素创建的 HTML 格式末尾的空格,否则如果有空格,您将在末尾得到一个粗大的字符串。
如果还有其他更有效的解决方案,我不知道,但欢迎提出建议。这就是我在代码中使用的内容,我相信它将具有高性能并满足我的需求。
vue 3
<template>
<p contenteditable @input="onInput" ref="p"></p>
{{ msg }}
</template>
<style scoped>
[contenteditable] {
border: 2px solid orange;
padding: 1rem;
font-size: 1.5rem;
}
[contenteditable]:focus {
background-color: bisque;
}
</style>
<script setup>
import { onMounted, ref } from "vue";
const msg = ref("hello world");
const p = ref(null);
onMounted(() => {
p.value.innerText = msg.value;
});
function onInput(e) {
msg.value = e.target.innerText;
}
</script>