代码之家  ›  专栏  ›  技术社区  ›  now_world

Vue模型未更新

  •  7
  • now_world  · 技术社区  · 8 年前

    当我尝试更新自定义文本区域组件的模型数据时 this.message='<span id="foo">bar</span> 文本和html不会像应该的那样显示在htmltextarea标记中,但我可以看到Vue开发工具控制台中应用的更新。我还尝试切换到对象而不是字符串,并使用 Vue.set ,但这也不起作用。

    有没有关于如何解决这个问题的建议?

    目标是 htmlTextArea 组件是从htmlTextArea标记中获取用户文本(这很有效),操作此文本并将其绑定回textarea,但其中包含HTML。

    自定义文本区域组件:

    <template>
      <div contenteditable="true" @input="updateHTML" class="textareaRoot"></div>
    </template>
    <script>
    export default {
      // Custom textarea 
      name: 'htmlTextArea',
      props:['value'],
      mounted: function () {
          this.$el.innerHTML = this.value;
      },
      methods: {
          updateHTML: function(e) {
              this.$emit('input', e.target.innerHTML);
          }
      }
    }
    </script>
    

    其他组件:

    <template>
    ...
    <htmlTextArea id="textarea" v-model="message"></htmlTextArea>
    ...
    </template>
    <script>
          data: {
            return {
              message: 'something'//this works
            }
          }
         ...
         methods: {
          changeText() {
            this.message='<span id="foo">bar</span>'//this does not
          }
         },
         components: {
             htmlTextArea
         }
    </script>
    
    2 回复  |  直到 8 年前
        1
  •  15
  •   Jacob Goh    8 年前

    您需要在 value 道具改变。你可以 watch 对于 价值 改变

    <template>
        <div contenteditable="true" @input="updateHTML" class="textareaRoot"></div>
    </template>
    <script>
    
    export default {
      // Custom textarea
      name: "htmlTextArea",
      props: ["value"],
      mounted: function() {
        this.$el.innerHTML = this.value;
      },
      watch: {
          value(v) {
              this.$el.innerHTML = v;
          }
      },
      methods: {
        updateHTML: function(e) {
          this.$emit("input", e.target.innerHTML);
        }
      }
    };
    </script>
    
        2
  •  3
  •   Brian Lee    8 年前

    更改 data 属性转换为函数,正如您所定义的那样,它不是被动的。

    data () {
        return {
            message: 'something'//this works 
        }
    }
    

    现在,当您更新 message 属性,则组件将相应更新。

    Reactivity in depth

    推荐文章