Capturing html wrapped by the component to set a data value in vue.js

Viewed 302

I am working on a tiptap based component. I want to take the html that is within the component tags

<vue-wysiwyg>
    <p>Hey, this is some test text.</p>
    <p>I should end up in editor.content</p>
</vue-wysiwyg>

And have the editor.content data for my component be given it.

export default {
  data() {
    return {
      editor: new Editor({
        content: '',
      }),
    }
  },
}

I thought about slots but that just passes through html, it doesn't capture it.

2 Answers

I think the slots are the way to go, but since they contain vdom objects we have to use vue to convert it into html. The following should work:

computed: {
    html(){

        return new Vue({ 
                render: h => h('div', {}, this.$slots.default)
            })
            .$mount().$el.innerHTML
    } 
}

We are creating simple component instance that has only a render function and than we $mount it to generate the DOM and than we extract the innerHTML from the root element.

NOTE: You would have to import Vue in this file

You can give the component a ref and access its inner HTML and assign it editor.content

<vue-wysiwyg ref="wysiwyg">
    <p>Hey, this is some test text.</p>
    <p>I should end up in editor.content</p>
</vue-wysiwyg>

And then in the mounted life cycle hook

export default {
  data() {
    return {
      editor: new Editor({
        content: '',
      }),
    }
  },
  mounted() {
    this.editor.content = this.$refs.wysiwyg.$el.innerHTML;
  }
}

Like this sandbox

Hope this helps

Related