如何在 v-html 中使用组件 [英] How to use components in v-html

查看:151
本文介绍了如何在 v-html 中使用组件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试使用 v-html 中的组件.我想从自己的 API 中获取 html,然后我会展示.

这是我的代码.

HTML:

<div id="应用程序"><span v-html="html"></span><徽章></徽章><span v-html="html2"></span><partial name="my-partial"></partial><span v-html="html3"></span>

Javascript:

Vue.component('徽章', {模板:'<span class="component-tag">这是组件</span>',})Vue.partial('my-partial', '<p>这是部分!</p>')//启动应用新的 Vue({el: '#app',数据: {html: '<p>这是 HTML</p>',html2: '<徽章></徽章>',html3: '<partial name="my-partial"></partial>'}})

https://jsfiddle.net/9w3kz6xm/4/

我尝试了部分,因为 Vue 文档说如果你需要重用模板片段,你应该使用部分."

它不起作用.也许是我弄错了,我不知道什么是错误.

谢谢.

解决方案

很确定 Vuejs 很难直接使用外部 html.v-html 将简单地替换 html 内容,因此不会执行任何指令.它的目的是为了避免此处记录的 XSS 攻击:https://vuejs.org/v2/guide/syntax.html#Raw-HTML

<块引用>

在您的网站上动态渲染任意 HTML 可能非常危险,因为它很容易导致 XSS 漏洞.仅对受信任的内容使用 HTML 插值,切勿对用户提供的内容使用.

如果您确实需要使用外部 html,则可以使用此处记录的 Vue.compile():https://vuejs.org/v2/api/#Vue-compile

可以在此处找到工作示例:https://jsfiddle.net/Linusborg/1zdzu7k1/及其相关讨论可以在这里找到:https://forum.vuejs.org/t/vue-compile-what-is-staticrenderfns-render-vs-staticrenderfns/3950/7

I am trying to use components in v-html. I want to get html from own API, then I will show that.

Here is my code.

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:

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/

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.

Thank you.

解决方案

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

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.

If you really need to use external html, it is possible to use Vue.compile() documented here: 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

这篇关于如何在 v-html 中使用组件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆