Categories
Vue Answers

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

Spread the love

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.

By John Au-Yeung

Web developer specializing in React, Vue, and front end development.

Leave a Reply

Your email address will not be published. Required fields are marked *