[Vuejs]-Convert long text string to proper HTML

0๐Ÿ‘

โœ…

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>

0๐Ÿ‘

Try use the directie v-html.

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

Leave a comment