How to do databind two way in v-html?

2020-02-15 03:42发布

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条回答
对你真心纯属浪费
2楼-- · 2020-02-15 04:12

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>

查看更多
登录 后发表回答