2👍
Unfortunately, contenteditable
doesn’t work with Vue
bindings such as v-model
, it’s recommended that you use a library such as medium.js to build your own component.
However, if you’re just trying to do something simple and keep the data in sync you can probably do that yourself:
View Model
new Vue({
el: '#app',
methods: {
updateMessage() {
this.message = this.$refs.message.innerText;
}
},
watch: {
message() {
this.$refs.message.innerText = this.message;
}
},
data: {
message: 'Hello'
}
})
HTML
<p ref="message" contenteditable="true" @keyup="updateMessage" class="editable">{{message}}</p>
As you can see you have to deal with updating the DOM yourself when using contenteditable
. What I’m actually doing here is using a ref to target the contenteditable, so I can get the inner text via this.$refs.message.innerText
. I’ve then added a @keyup
event which calls the updateMessage
method to update the message
data property. I’ve then added a watcher
which reverses this process, so when message is updated it updates the contenteditable.
Here’s the JSFiddle: https://jsfiddle.net/3ngc9486/
0👍
Yes it has a two-way binding directive v-model
, but it works only with input elements. So, instead of using a p
element and handling that with complex JS, use a textarea
with v-model
and it will work out of the box.
<textarea v-model="message"></textarea>
here is an example.