首页 > 解决方案 > Vue动态加载组件并高亮代码预览并保留HTML结构

问题描述

我试图动态加载 vue 组件,当组件可见时,它应该将组件的 HTML 显示为代码预览。

这是成功的并且正在工作,但显示一个大字符串,因为我使用 $el.innnerHTML。我想要的是组件/html的结构应该反映在代码预览中。

这是现在的结果:

在此处输入图像描述

我想要的是:

在此处输入图像描述

<!DOCTYPE html>
<html lang="en">

<head>
  <meta charset="UTF-8" />
  <meta name="viewport" content="width=device-width, initial-scale=1.0" />
  <meta http-equiv="X-UA-Compatible" content="ie=edge" />
  <title>Document</title>
  <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.4.1/css/bootstrap.min.css"
    integrity="sha384-Vkoo8x4CGsO3+Hhxv8T/Q5PaXtkKtu6ug5TOeNV6gBiFeWPGFN9MuhOf23Q9Ifjh" crossorigin="anonymous" />
  <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/prism/1.14.0/themes/prism.min.css" />
</head>

<body>
  <div id="app" class="container mt-5">
    <div class="row">
      <div class="col-12">

        <select v-model="selected" @change="onChange">
          <option disabled value="">Please select one</option>
          <option value="componentOne">A</option>
          <option value="componentTwo">B</option>
        </select>

        <component :is="selected" :ref="mychildcomponent"></component>
        <code-highlight :code="codeHighlight"></code-highlight>

      </div>
    </div>
  </div>

  <script src="https://cdn.jsdelivr.net/npm/vue/dist/vue.js"></script>
  <script src="https://cdnjs.cloudflare.com/ajax/libs/prism/1.14.0/prism.min.js"></script>

  <script>
    Vue.component("componentOne", {
      template: `
        <div>
          <div>
            <p>Home component</p>
          </div>
        </div>
        `
    });

    Vue.component("componentTwo", {
      template: `
        <div>
          <div>
            <p>Posts component</p>
          </div>
        </div>
      `
    });

    Vue.component("code-highlight", {
      props: ["code"],
      template: "<pre class='language-markup'><code class='language-markup' v-html='highlightedCode'></code></pre>",
      computed: {
        highlightedCode: function () {
          return Prism.highlight(this.code, Prism.languages.javascript);
        }
      },
    });

    new Vue({
      el: "#app",
      data: {
        selected: "",
        mychildcomponent: "mychildcomponent",
        codeHighlight: ""
      },
      methods: {
        onChange() {
          setTimeout(() => {
            this.codeHighlight = this.$refs.mychildcomponent.$el.innerHTML;
          })
        }
      }
    });
  </script>
</body>

</html>

例子

这是一个JSFiddle

标签: javascripthtmlvue.jsvue-componentcodemirror

解决方案


您可以使用<pre>如下标签:

Vue.component("componentOne", {
      template: `
        <pre>
          <div>
            <p>Home component</p>
          </div>
        </pre>
        `
    });

<PRE>标签将按原样在网页上显示文本。


推荐阅读