【问题标题】:How Do You Prevent Raw HTML from Rendering in Vue.js如何防止原始 HTML 在 Vue.js 中呈现
【发布时间】:2020-07-10 19:32:13
【问题描述】:

我正在尝试让我的 Vue.js 应用程序呈现原始 html 而不是代码本身。

来自服务器的代码如下所示:

<a href="http://google.com">Google</a>

但是当它被渲染时,html代码被解释为文本而不是代码

<a href="http://google.com">Google</a>

我尝试过使用 v-html、decodeURIComponent 和过滤器,但没有成功:

是否可以从数据库中获取转义代码并在 Vue.js 中将其呈现为原始 html?

【问题讨论】:

  • 请告诉我们你是如何尝试 v-html 的。

标签: javascript vue.js nuxt.js


【解决方案1】:

在 v-html 中传递它

<span v-html="here_your_html"></span>

更新

我看到您的问题与转义内容有关。尝试使用以下方法:unescape(your_html);

喜欢:

<span v-html="unescape(here_your_html)"></span>

在你的方法中:

unescaunescapepeS(string) {

  //create an element with that html
  var e = document.createElement("textarea");
   
  //get the html from the created element
  e.innerHTML = string;

  return e.childNodes.length === 0 ? "" : e.childNodes[0].nodeValue;
}

这里是一个沙箱: https://codesandbox.io/s/hopeful-curran-116fm?file=/src/App.vue

希望这会有所帮助!

【讨论】:

    【解决方案2】:

    当您的 HTML 从服务器加载时,您需要类似 v-runtime-template 的内容。这是开始的示例。

    <template>
      <div>
        <v-runtime-template :template="template"/>
      </div>
    </template>
    
    <script>
    import VRuntimeTemplate from "v-runtime-template";
    
    export default {
      data: () => ({
        template: `
          <app-title>Howdy Yo!</app-title>
          <vue-router to="/croco-fantasy">Go to the croco-fantasy</vue-router>
        `
      }),
    };
    </script>
    

    v-runtime-template 自动获取使用它的父组件的上下文,然后它使用动态组件让 Vue 编译和附加。这是完整的Article

    【讨论】:

      猜你喜欢
      • 2016-04-26
      • 2019-08-29
      • 2020-04-21
      • 2022-10-14
      • 1970-01-01
      • 2011-03-02
      • 2021-08-20
      • 2011-01-12
      • 1970-01-01
      相关资源
      最近更新 更多