Преобразовать длинную текстовую строку в правильную HTML - PullRequest
0 голосов
/ 29 января 2020

Скажем, у меня есть длинная строка из текстового редактора wysiwyg.

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>'

Есть ли способ Vue превратить эту строку в структурированную HTML?

Я хочу создайте массив элементов h2 из исходной строки, а затем передайте массив дочернему компоненту в качестве реквизита.

Ответы [ 2 ]

0 голосов
/ 30 января 2020

Хотите что-то подобное:

<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 голосов
/ 29 января 2020

Попробуйте использовать прямое ie v- html.

Внимание: обратите внимание, что содержимое вставлено как обычный HTML - оно не будет скомпилировано как Vue шаблоны.

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...