Welcome toVigges Developer Community-Open, Learning,Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
1.7k views
in Technique[技术] by (71.8m points)

vue.js - How to do databind two way in v-html?

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?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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>

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to Vigges Developer Community for programmer and developer-Open, Learning and Share
...