VueJS 使用 v-html 在 html 字符串中呈现属性 [英] VueJS render property inside html string using v-html
问题描述
我有一个从编辑器获取并存储在数据库中的 html 字符串.
I have a string of html where I get from Editor and stored in the database.
<h3><a href="#" rel="noopener noreferrer nofollow"><em><strong>用户资料:</strong></em><;/a></h3><p></p><p>{{user}}</p>
我想从数据库中检索它并将其呈现为 HTML.当我使用 v-html 时,它将呈现为:
<v-card-text v-html="content"></v-card-text>
用户简介:
{{user}}
如果我有这样的数据属性,如何从数据属性呈现 {{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>"
};
},
预期结果:
用户简介:
Lim Socheat
Lim Socheat
因为 {{ user }} 将呈现为 Lim Socheat
推荐答案
使内容成为计算属性.然后像这样使用它:
Make content a computed property. And then use it like this:
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>';
}
}
您可以通过这种方式使用数据中定义的所有变量.
You can use all variables defined in data in this way.
更新:由于 OP 从后端获取 HTML 字符串,因此在这种情况下他们需要替换变量.我们保留了可能出现的所有变量的映射,然后我们正在动态创建一个 Regex 以替换代码中的所述键.
Update: Since OP is getting the HTML string from backend, they need to replace the variables in this case. We have kept a map of all variables that might come and then we are creating a Regex dynamically to replace the said key from code.
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;
}
}
这篇关于VueJS 使用 v-html 在 html 字符串中呈现属性的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!