Convert long text string to proper HTML

474 views Asked by At

Say I have a long string from a wysiwyg text editor.

var string = '<div class="section"><h2 #id="section1">Find the thing</h2><p>Here is a paragraph.</p><img src="https://via.placeholder.com/150"><p>Here is a second paragraph</p><p>Woah, you mean to tell me there's three paragraphs!</p></div><div class="section"><h2 #id="section2">Find the thing</h2><p>Here is a paragraph.</p><img src="https://via.placeholder.com/150"><p>Here is a second paragraph</p><p>Woah, you mean to tell me there's three paragraphs!</p></div><div class="section"><h2 #id="section3">Find the thing</h2><p>Here is a paragraph.</p><img src="https://via.placeholder.com/150"><p>Here is a second paragraph</p><p>Woah, you mean to tell me there's three paragraphs!</p></div>'

Is there a Vue way to turn that string into structured HTML?

I want to create an array of the h2 elements from the original string and then pass the array to a child component as a prop.

2

There are 2 answers

1
Gabriel Willemann On BEST ANSWER

Do you want something like that:

<template>
  <div>
    <child :h2Elements="h2Elements" />
  </div>
</template>

<script>
import child from './components/child.vue';

export default {
  name: 'app',
  components: { child },
  data() {
    return {
      h2Elements: [],
    };
  },
  mounted() {
    let myRoot = document.createElement('div');
    myRoot.innerHTML = `<div class="section"><h2 #id="section1">Find the thing</h2><p>Here is a paragraph.</p><img src="https://via.placeholder.com/150"><p>Here is a second paragraph</p><p>Woah, you mean to tell me there's three paragraphs!</p></div><div class="section"><h2 #id="section2">Find the thing</h2><p>Here is a paragraph.</p><img src="https://via.placeholder.com/150"><p>Here is a second paragraph</p><p>Woah, you mean to tell me there's three paragraphs!</p></div><div class="section"><h2 #id="section3">Find the thing</h2><p>Here is a paragraph.</p><img src="https://via.placeholder.com/150"><p>Here is a second paragraph</p><p>Woah, you mean to tell me there's three paragraphs!</p></div>`;
    for (let div of myRoot.childNodes) {
      let [h2] = div.getElementsByTagName('h2');
      this.h2Elements.push(h2);
    }
  },
};
</script>
<template>
  <div>{{ h2Elements.map(h2 => h2.innerText) }}</div>
</template>

<script>
export default {
  name: 'child',
  props: ['h2Elements'],
};
</script>
2
Gabriel Willemann On

Try use the directie v-html.

Attention: Note that the contents are inserted as plain HTML - they will not be compiled as Vue templates.