如何在v-html中使用组件 [英] How to use components in v-html
问题描述
我正在尝试使用v-html中的组件. 我想从自己的API获取html,然后将显示该内容.
I am trying to use components in v-html. I want to get html from own API, then I will show that.
这是我的代码.
HTML:
<!-- app -->
<div id="app">
<span v-html="html"></span>
<badge></badge>
<span v-html="html2"></span>
<partial name="my-partial"></partial>
<span v-html="html3"></span>
</div>
JavaScript:
Javascript:
Vue.component('badge', {
template: '<span class="component-tag">This is component</span>',
})
Vue.partial('my-partial', '<p>This is a partial!</p>')
// start app
new Vue({
el: '#app',
data: {
html: '<p>THIS IS HTML</p>',
html2: '<badge></badge>',
html3: '<partial name="my-partial"></partial>'
}
})
https://jsfiddle.net/9w3kz6xm/4/
我尝试了局部函数,因为Vue文档说:如果需要重用模板,则应该使用局部函数."
I tried partials because Vue document says " If you need to reuse template pieces, you should use partials."
它不起作用.也许我在犯错,我不知道这是什么错误.
It does not work. Maybe I am making mistake, I don't know what is a mistake.
谢谢.
推荐答案
很确定Vuejs使得直接使用外部html变得非常困难. v-html
将仅替换html内容,因此将不执行任何指令.它的目的是避免此处记录的XSS攻击: https://vuejs. org/v2/guide/syntax.html#Raw-HTML
Pretty sure Vuejs makes it very hard to directly use external html. v-html
will simply replace the html content and therefore will not execute any directive. The purpose of it is to avoid XSS attacks as documented here: https://vuejs.org/v2/guide/syntax.html#Raw-HTML
在网站上动态呈现任意HTML可能非常危险,因为它很容易导致XSS漏洞.仅在受信任的内容上使用HTML插值,而不在用户提供的内容上使用.
Dynamically rendering arbitrary HTML on your website can be very dangerous because it can easily lead to XSS vulnerabilities. Only use HTML interpolation on trusted content and never on user-provided content.
如果您确实需要使用外部html,则可以使用此处记录的Vue.compile()
: https://vuejs.org/v2/api/#Vue-compile
If you really need to use external html, it is possible to use Vue.compile()
documented here: https://vuejs.org/v2/api/#Vue-compile
可以在此处找到一个工作示例: https://jsfiddle.net/Linusborg/1zdzu7k1/ 及其相关的讨论可以在这里找到:
A working example can be found here: https://jsfiddle.net/Linusborg/1zdzu7k1/ and its related discussion can be found here: https://forum.vuejs.org/t/vue-compile-what-is-staticrenderfns-render-vs-staticrenderfns/3950/7
这篇关于如何在v-html中使用组件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!