简体   繁体   English

contenteditable div附加一个html元素并在Vuejs中对其进行v-model

[英]contenteditable div append a html element and v-model it in Vuejs

Here is my Html code. 这是我的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>

Here is js part 这是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>';
        }
    }
});

The problem is, when I click the button to push a html tag(img) to my variable (html) and it works. 问题是,当我单击按钮将html标记(img)推送到变量(html)时,它起作用了。 but after typing, it will remove the tag part that was insert. 但输入后,它将删除插入的标签部分。 Is that any way to append to html code successful in Vue? 有什么办法可以在Vue中成功附加到html代码吗?

Here is the codepen example https://codepen.io/weretyc/pen/EwXZYL?editors=1010 这是codepen示例https://codepen.io/weretyc/pen/EwXZYL?editors=1010

The main problem: The html disappears because of this.html = e.target.innerText; 主要问题:由于this.html = e.target.innerText; html消失了this.html = e.target.innerText; . Instead, use this.html = e.target.innerHTML; 而是使用this.html = e.target.innerHTML; . innerHTML resolves to the full HTML content. innerHTML解析为完整的HTML内容。

Secondary Problem: After typing, the cursor focuses the beginning of the div. 次要问题:键入后,光标将焦点对准div的开头 This is because v-html causes the div to update. 这是因为v-html导致div更新。

To solve, ensure that v-html only updates the div on focusout. 要解决此问题,请确保v-html仅在焦点输出时更新div。

Full Example 完整的例子

 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> 

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM