gpt4 book ai didi

vue.js - 当 VueJS 计算属性返回 HTML 代码时如何处理?

转载 作者:搜寻专家 更新时间:2023-10-30 22:09:14 24 4
gpt4 key购买 nike

我使用 VueJS 2 来呈现和计算表单项。现在,如果属性小于 10,我需要显示一个数字;如果属性大于或等于 10,我需要显示一条文本消息。

我使用这段代码:

Vue.component('mycomponent', {
template: '#mytemp',
data: function() {
// ...
},
computed: {
mycomputedprop: function() {
if (this.model_a < 10) {
return '<span class="numbervalue">' + this.model_a + '€</span>';
} else {
return '<span class="textvalue">I\'ll contact you as soon as possible!</span>';
}
}
}
});

我使用这段代码来显示值:

<div id="app">
{{ mycomputedprop }}
</div>

问题是:如果我显示这个值,它会将 HTML 代码显示为文本,而不是 HTML。如何将返回值显示为 HTML 代码?

最佳答案

你可以使用v-html

文档:Raw-HTML

<div id="app">
<div v-html="mycomputedprop"></div>
</div>

The contents of this div will be replaced with the value of therawHtml property, interpreted as plain HTML - data bindings areignored. Note that you cannot use v-html to compose template partials,because Vue is not a string-based templating engine. Instead,components are preferred as the fundamental unit for UI reuse andcomposition.

Vue 3 示例:

const RenderHtmlApp = {
data() {
return {
rawHtml: '<span style="color: red">This should be red.</span>'
}
}
}

Vue.createApp(RenderHtmlApp).mount('#example1')
<script src="https://unpkg.com/vue@next"></script>
<div id="example1">
<p>Using mustaches: {{ rawHtml }}</p>
<p>Using v-html directive: <span v-html="rawHtml"></span></p>
</div>

关于vue.js - 当 VueJS 计算属性返回 HTML 代码时如何处理?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44804058/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com