Vuejs Computed Setter 与对象双向数据绑定

Vuejs Computed Setter with an object two way data binding

遵循双向数据绑定如何工作的基本示例:

<template>
<input v-model="fullname"/>
<input v-model="first"/>
<input v-model="last"/>
</template>
<script>
    var app = new Vue({
      el: '#app',
      data: {
        first: '',
        last: ''
      },
      computed: {
        fullname: {
          // getter function
          get: function() {
            return this.first + " " + this.last
          },
          // setter function
          set: function(value) {
            var name = value.split(' ')
            this.first = name[0]
            this.last = name[1]
          }
        }
      }
    })
</script>

如此处所示:https://youtu.be/PuxdMnk-u5k?t=17m43s (17:43) - 您可以轻松修改全名输入中的名字和姓氏数据。

现在我的情况有点不同。我有一个对象如下:

myObject: [
   {active: true, itemId: "55", text: 'some text', textOutput: ''}
   {active: true, itemId: "56", text: 'some text', textOutput: ''}
   {active: true, itemId: "58", text: 'some text', textOutput: ''}
   {active: true, itemId: "65", text: 'some text', textOutput: ''}
   {active: true, itemId: "105", text: 'some text', textOutput: ''}
]

接下来我通过计算稍微修改一下 - 这里只需添加到每个项目 <li> 标签:

modifyArrayItem () {
  var output=''
    for (var i=0; i<this.myObject.length; i++) {
      if (this.myObject[i].active) {
        this.myObject[i].textOutput= '<li>' + this.myObject[i].text + '</li>'
        output = output + this.myObject[i].textOutput
      }
      else {
        this.myObject[i].textInput = ''
      }          
    }
    return output
  }, 

然后通过 v-html

只输出活动项目
<div  v-html="modifyArrayItem"></div>

到目前为止很简单。现在我希望能够在我的 html 中编辑输出,比如像这样的 quill-editor:

<quill-editor v-model="modifyArrayItem" :options="options"></quill-editor>

能做到吗?

我应该怎么做才能根据我的羽毛笔编辑器字段中的 itemId 数字编辑 myObject[n-element].textmyObject[n-element].textOutput? (请注意[n-element] != itemId)。

如何在编辑时将每个元素的myObject.active动态更改为true/false,如何防止编辑数据丢失?如何将编辑后的文本保存到单独的变量中?

编辑:一些想法 - 为每个 <li>?

添加某种带有 itemId 值的隐形标签到 quill-editor

是的,这是可能的。您可以将 HTML 解析为行,并将这些行分配给它们在 myObject.

中的相应条目

但是请注意,每次键入内容时更新编辑器的内容会导致光标移动到编辑器的开头。

事实证明,quill 有获取和设置选择位置的方法。它变得有点毛茸茸,因为每个编辑调用设置两次,所以你必须检查是否有任何实际变化。但这有效:

modifyArrayItem: {
  get() {
    return this.myObject.map(o => "<li>" + o.text + "</li>").join("");
  },
  set(newValue) {
    const oldLines = this.myObject.map((o) => o.text);
    const lines = newValue.split("</p>")
      .map((p) => p.replace('<p>', ''));
    const same = oldLines.join('') === lines.join('');

    if (!same) {
      const pos = this.$refs.quill.quill.getSelection();
      for (let i=0; i < this.myObject.length; ++i) {
        this.myObject[i].text = lines[i];
      }
      this.$nextTick(() => {
        this.$refs.quill.quill.setSelection(pos);
      });
    }
  }
}

Updated codepen