Vue 2内容可通过v模型编辑

Sou*_*uet 5 javascript contenteditable vue.js

我正在尝试使文本编辑器类似于Medium。我正在使用内容可编辑的段落标签,并将每个项目存储在数组中,并使用v-for呈现每个项目。但是,我在使用v-model将文本与数组绑定时遇到问题。似乎与v模型和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>
Run Code Online (Sandbox Code Playgroud)

在我的脚本中:

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);
         }
      }
   }
}
Run Code Online (Sandbox Code Playgroud)

我还没有在网上找到任何答案。

Dav*_*don 12

我尝试了一个示例,并且eslint-plugin-vue报告说元素v-model不支持p。请参阅有效的v模型规则。

在撰写本文时,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>
Run Code Online (Sandbox Code Playgroud)

创建一个可重用的可编辑组件

Editable.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>
Run Code Online (Sandbox Code Playgroud)

索引值

<template>
  <Editable v-model="content" />
</template>

<script>
import Editable from '~/components/Editable';

export default {
  components: { Editable },
  data() {
    return { content: 'hello world' };
  },
};
</script>
Run Code Online (Sandbox Code Playgroud)

针对您特定问题的定制解决方案

经过多次迭代,我发现对于您的用例而言,使用单独的组件会更容易获得可行的解决方案。contenteditable元素似乎非常棘手-尤其是在列表中呈现时。我发现删除后必须手动更新innerText每个文件p,以使其正常工作。我还发现使用id可以工作,但不能使用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>
Run Code Online (Sandbox Code Playgroud)


Alm*_*itt 10

我想我可能想出了一个更简单的解决方案。见下面的片段:

<!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>
Run Code Online (Sandbox Code Playgroud)

解释:

您可以编辑跨度,因为我添加了标签contenteditable。请注意,在 上input,我将调用 handleInput 函数,该函数将内容的 innerHtml 设置为您插入到可编辑范围中的任何内容。然后,要添加粗体功能,您只需选择要加粗的内容并单击粗体按钮。

添加奖金!它也适用于 cmd+b ;)

希望这对某人有所帮助!

快乐编码

请注意,我通过 CDN 引入了用于样式和 vue 的 bootstrap css,以便它可以在代码段中运行。

  • 咳咳,毕竟不是那么完美。当内容是静态时它会起作用,但是一旦从模型中获取内容,一旦您输入任何内容,插入符号就会转到文本的开头。 (3认同)
  • 我正在重置插入符位置,效果很好:handleInput: (e) =&gt; { const sel = document.getSelection(); const offset = sel.anchorOffset; this.content = e.target.textContent; app.$nextTick(() =&gt; { sel.collapse(sel.anchorNode, offset); }); } (2认同)

小智 5

您可以使用 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
      });
    },
  }
});
Run Code Online (Sandbox Code Playgroud)
<script src="https://unpkg.com/vue@2.6.10/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>
  <button class="toolbar" v-on:click.prevent="stylize('italic')">ITALIC</button>
  <button class="toolbar" v-on:click.prevent="stylize('justifyLeft')">LEFT ALIGN</button>
  <button class="toolbar" v-on:click.prevent="stylize('justifyCenter')">CENTER</button>
  <button class="toolbar" v-on:click.prevent="stylize('justifyRight')">RIGHT ALIGN</button>
  <button class="toolbar" v-on:click.prevent="stylize('insertOrderedList')">ORDERED LIST</button>
  <button class="toolbar" v-on:click.prevent="stylize('insertUnorderedList')">UNORDERED LIST</button>
  <button class="toolbar" v-on:click.prevent="stylize('backColor',false,'#FFFF66')">HEIGHLIGHT</button>
  <button class="toolbar" v-on:click.prevent="stylize('foreColor',false,'red')">RED TEXT</button>
  <button class="toolbar" v-on:click.prevent="createLink()">CREATE LINK</button>
  <button class="toolbar" v-on:click.prevent="stylize('unlink')">REMOVE LINK</button>
  <button class="toolbar" v-on:click.prevent="stylize('formatBlock',false,'H1')">H1</button>
  <button class="toolbar" v-on:click.prevent="stylize('formatBlock',false,'BLOCKQUOTE')">BLOCK QUOTE</button>
  <button class="toolbar" v-on:click.prevent="stylize('underline')">UNDERLINE</button>
  <button class="toolbar" v-on:click.prevent="stylize('strikeThrough')">STRIKETHROUGH</button>
  <button class="toolbar" v-on:click.prevent="stylize('superscript')">SUPERSCRIPT</button>
  <button class="toolbar" v-on:click.prevent="stylize('subscript')">SUBSCRIPT</button>
  <button class="toolbar" v-on:click.prevent="stylize('indent')">INDENT</button>
  <button class="toolbar" v-on:click.prevent="stylize('outdent')">OUTDENT</button>
  <button class="toolbar" v-on:click.prevent="stylize('insertHorizontalRule')">HORIZONTAL LINE</button>
  <button class="toolbar" v-on:click.prevent="stylize('insertParagraph')">INSERT PARAGRAPH</button>
  <button class="toolbar" v-on:click.prevent="stylize('selectAll')">SELECT ALL</button>
  <button class="toolbar" v-on:click.prevent="stylize('removeFormat')">REMOVE FORMAT</button>
  <button class="toolbar" v-on:click.prevent="stylize('undo')">UNDO</button>
  <button class="toolbar" v-on:click.prevent="stylize('redo')">REDO</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>
Run Code Online (Sandbox Code Playgroud)


Sou*_*uet 2

我昨天就明白了!确定了这个解决方案。我基本上只是通过更新任何可能的事件来手动跟踪数组中的innerHTML content,并通过手动分配带有动态引用的相应元素来重新渲染,例如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>
Run Code Online (Sandbox Code Playgroud)