Javascript 如何在 v-html 中使用组件
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/37133282/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to use components in v-html
提问by Takumi Sato
I am trying to use components in v-html. I want to get html from own API, then I will show that.
我正在尝试在 v-html 中使用组件。我想从自己的 API 获取 html,然后我会展示它。
Here is my code.
这是我的代码。
HTML:
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/
https://jsfiddle.net/9w3kz6xm/4/
I tried partials because Vue document says " If you need to reuse template pieces, you should use partials."
我尝试了部分,因为 Vue 文档说“如果你需要重用模板片段,你应该使用部分。”
It does not work. Maybe I am making mistake, I don't know what is a mistake.
这是行不通的。也许我犯了错误,我不知道什么是错误。
Thank you.
谢谢你。
回答by Costa Huang
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
非常肯定 Vuejs 很难直接使用外部 html。v-html
将简单地替换 html 内容,因此不会执行任何指令。它的目的是避免此处记录的 XSS 攻击:https: //vuejs.org/v2/guide/syntax.html#Raw-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 可能非常危险,因为它很容易导致 XSS 漏洞。仅对受信任的内容使用 HTML 插值,切勿对用户提供的内容使用。
If you really need to use external html, it is possible to use Vue.compile()
documented here: https://vuejs.org/v2/api/#Vue-compile
如果你真的需要使用外部 html,可以使用Vue.compile()
这里记录的:https: //vuejs.org/v2/api/#Vue-compile
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
可以在此处找到工作示例:https: //jsfiddle.net/Linusborg/1zdzu7k1/及其相关讨论可以在此处找到:https: //forum.vuejs.org/t/vue-compile-what-is-staticrenderfns -render-vs-staticrenderfns/3950/7