Categories
JavaScript Answers Vue Vue Answers

How to get the content of a contentEditable element with Vue.

Spread the love

Sometimes, we want to get the content of a contentEditable element with Vue.js.

In this article, we’ll look at how to get the content of a contentEditable element with Vue.js.

How to get the content of a contentEditable element with Vue.js?

To get the content of a contentEditable element with Vue.js, we can listen to the input event on the contentEditable element.

For instance, we write:

<script src="https://cdn.jsdelivr.net/npm/vue@2/dist/vue.js"></script>

<div id='app'>

</div>

to add the Vue script and app container.

Then we write:

const v = new Vue({
  el: '#app',
  template: `
    <p
      contenteditable
      @input="onInput"
    >
      {{ content }}
    </p>
  `,
  data: {
    content: 'hello world'
  },
  methods: {
    onInput(e) {
      console.log(e.target.innerText);
    },
  },
})

We have a contentEditable p element.

And we listen to the input event with @input="onInput".

And we get the content of the div when it’s being changed with e.target.innerText.

We put the initial content of the p element in content.

Conclusion

To get the content of a contentEditable element with Vue.js, we can listen to the input event on the contentEditable element.

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 *