这是我的HTML代码。
<div id="app">
<button @click="renderHtml">clisdfsdfsdfck to appen html</button>
<div class="flex">
<div class="message" @input="fakeVmodel" v-html="html" contenteditable="true"></div>
<div class="message">{{ html }}</div>
</div>
</div>
这是JS部分
let app = new Vue({
el: '#app',
data: {
html: 'some text',
},
methods: {
fakeVmodel: function(e){
this.html = e.target.innerText;
},
renderHtml: function(){
this.html += '<img src="https://cdn-images-1.medium.com/max/853/1*FH12a2fX61aHOn39pff9vA.jpeg" alt="" width=200px>';
}
}
});
问题是,当我单击按钮以将HTML标签(IMG)推向我的变量(HTML)时,它起作用。但是键入后,它将删除插入的标签部分。这是否可以将HTML代码成功地添加到VUE中?
这是Codepen示例https://codepen.io/weretyc/pen/ewxzyl?editors=1010
主要问题:HTML由于this.html = e.target.innerText;
而消失。而是使用this.html = e.target.innerHTML;
。innerHTML
解决了完整的HTML内容。
次要问题:键入后,光标将DIV的开始开始。这是因为v-html
导致DIV更新。
要解决,请确保v-html
仅更新focusOut的div。
完整示例
let app = new Vue({
el: '#app',
data: {
html: 'some text',
},
methods: {
updateHtml: function(e) {
this.html = e.target.innerHTML;
},
renderHtml: function(){
this.html += '<img src="https://cdn-images-1.medium.com/max/853/1*FH12a2fX61aHOn39pff9vA.jpeg" alt="" width=200px>';
}
}
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.4.4/vue.js"></script>
<div id="app">
<button @click="renderHtml">click to append html</button>
<div class="flex">
<div class="message" @focusout="updateHtml" v-html="html" contenteditable="true"></div>
<br>
<div class="message">{{ html }}</div>
</div>
</div>