Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
588 views
in Technique[技术] by (71.8m points)

javascript - How to use components in v-html

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.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...