当我尝试更新自定义文本区域组件的模型数据时 this.message='<span id="foo">bar</span>
文本和 html 没有像它应该的那样显示在 htmltextarea 标签中,但我可以看到在 Vue 开发工具的控制台中应用了更新。我也试过切换到对象而不是字符串并使用 Vue.set , 但这也不起作用。
关于如何解决这个问题有什么建议吗?
htmlTextArea
的目标组件是从 htmlTextArea 标签中获取用户文本(这有效),操作此文本并将其绑定(bind)回文本区域,但其中包含 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>
最佳答案
您需要在 value
属性更改后显式设置值。你可以watch为 value
改变。
<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>
关于vue.js - Vue模型不更新,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49809545/