How to use v-model with contenteditable elements in Vue.js?

Sometimes, we want to use v-model with contenteditable elements in Vue.js.

In this article, we’ll look at how to use v-model with contenteditable elements in Vue.js.

How to use v-model with contenteditable elements in Vue.js?

To use v-model with contenteditable elements in Vue.js, we should replace it with @input and put the content into the element itself.

For instance, we write

<template>
  <p contenteditable @input="onInput">
    {{ content }}
  </p>
</template>

<script>
export default {
  data() {
    return { content: "hello world" };
  },
  methods: {
    onInput(e) {
      console.log(e.target.innerText);
    },
  },
};
</script>

to set @input to onInput to watch for changes in the content of the contenteditable p element.

In onInput, we get the content of the p element with e.target.innerText.

Conclusion

To use v-model with contenteditable elements in Vue.js, we should replace it with @input and put the content into the element itself.