How to do databind two way in v-html?

邮差的信 提交于 2019-11-28 10:29:26

问题


I have an element div with atribute contenteditable="true". This div behaves like an element textarea.

<div v-on:keyup.enter="SendMensage" v-html="msg" contenteditable="true"></div>

my code:

data() {
     return {
        msg: '',
     }
},

methods: {
     enviaMensagem() {

        console.log(this.msg);

     }
}

My problem is that the databind does not work. What is typed in the div does not reflect on the variable. Does anyone know what can it be?


回答1:


You need to listen to changes of the element, because v-model only works on <textarea> or <input>. You can do this by using an @input listener.

The markup you get like this will be escaped. If you want to unescape it, you can use e.g. this approach. Then, you actually have the markup right next to the pseudo-textarea field. So, why not using a <textarea> from begin with?

new Vue({
  el: '#editor',
  data: {
    msg: ''
  },
  methods: {
    typing: function(el) {
      this.msg = el.target.innerHTML;
    },
    submit: function() {
      console.log("Submitting: ", this.msg);
    }
  }
});
.input {
  display: inline-block;
  vertical-align: middle;
  border: 1px solid black;
  width: 200px;
  height: 100px;
}
.output {
  display: inline-block;
  vertical-align: middle;
  width: 200px;
  height: 100px;
  background: #eee;
}
<script type="text/javascript" src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.3.3/vue.min.js"></script>

<div id="editor">
  <div class="input" @input="typing" @keyup.enter="submit" contenteditable="true"></div>
  <div class="output" v-html="msg"></div>
</div>


来源:https://stackoverflow.com/questions/44376484/how-to-do-databind-two-way-in-v-html

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!