VueJS 使用 v-html 在 html 字符串中呈现属性

Lim*_*eat 2 vue.js nuxt.js

编辑内容

我有一个 html 字符串,我从编辑器获取并存储在数据库中。

<h3><a href="#" rel="noopener noreferrer nofollow"><em><strong>Profile Of User:</strong></em></a></h3><p></p><p>{{user}}</p>

我想从数据库中检索它并将其呈现为 HTML。当我使用 v-html 时,它将呈现为:

<v-card-text v-html="content"></v-card-text>
Run Code Online (Sandbox Code Playgroud)

用户简介:

{{用户}}

如果我有这样的数据属性,如何从数据属性呈现 {{hello}}:

data() {
        return {
            user: "Lim Socheat",
            content:"<h3><a href="#" rel="noopener noreferrer nofollow"><em><strong>Profile Of User:</strong></em></a></h3><p></p><p>{{user}}</p>"
        };
    },
Run Code Online (Sandbox Code Playgroud)

预期结果:

用户简介:

林索契

因为{{ user }}会被渲染为Lim Socheat

Vij*_*shi 5

使内容成为计算属性。然后像这样使用它:

  computed: {
    content() {
       return '<h3><a href="#" rel="noopener noreferrer nofollow"><em><strong>Profile Of User:</strong></em></a></h3><p></p><p>' + this.user + '</p>';
    }
  }
Run Code Online (Sandbox Code Playgroud)

您可以通过这种方式使用数据中定义的所有变量。

更新: 由于 OP 从后端获取 HTML 字符串,因此在这种情况下他们需要替换变量。我们保留了可能出现的所有变量的映射,然后我们动态创建了一个正则表达式来替换代码中的所述键。

  computed: {
    content() {
      // keep a map of all your variables
      let valueMap = {
        user: this.user,
        otherKey: 250
      };
      let value = '<h3><a href="#" rel="noopener noreferrer nofollow"><em><strong>Profile Of User:</strong></em></a></h3><p></p><p>{{user}}</p>';
      let allKeys = Object.keys(valueMap);
      allKeys.forEach((key) => {
        var myRegExp = new RegExp('{{' + key + '}}','i');
        value = value.replace(myRegExp, valueMap[key]);
      });
      return value;
    }
  }
Run Code Online (Sandbox Code Playgroud)