简体   繁体   中英

vue.js - escape html inside slot

I am currently working on a component that looks like this:

  <pre v-highlightjs>
    <code>
      <slot></slot>
    </code>
  </pre>

So the problem I have is that when I am writing html inside the slot, this html is rendered and not shown as a string or code-sample in my case. I have tested it with escaped < and > and it works. How can I access the html inside the slot and escape it automatically?

Thank you

EDIT:

I use highlight.js for that component to highlight the code inside my component. highlight.js can highlight html aswell. When I put eg

<html><head></head><body></body></html> 

inside my slot, the box is shown, but the input is rendered as html. So I want to escape the html-Tags (and other code-snippets) so that it is shown and ofc highlighted. Hope that specifies my problem a bit more.

An important limitation to be aware of is that your HTML is not HTML, it is input to Vue's templating engine, so what a component sees in the slot may not be exactly what is in the HTML file.

Writing a directive to take HTML content and replace it with a text version of that content is pretty straightforward. Putting that in a component is also pretty straightforward. You can see these together in the snippet below.

What you will also see is that the Vue templating engine strips out tags that shouldn't be inside the body : the html , head , and body tags don't make it to the component. Their contents, if any, remain.

If it is important to be able to use those tags (or, for that matter, possibly invalid HTML), you will not be able to do it in a slot. You will need to have the HTML as a data string, which you can easily interpolate using the normal curlies.

 new Vue({ el: '#app', data: { headContent: 'Something in the head' }, components: { htmlEscaper: { template: '#html-escaper', directives: { escapeContent: { bind(el) { const html = el.innerHTML; el.textContent = html; } } } } } }); 
 <script src="//cdnjs.cloudflare.com/ajax/libs/vue/2.4.2/vue.min.js"></script> <div id="app"> <html-escaper> <html> <head> {{ headContent }} </head> <some-junk> Custom tags are ok </some-junk> <body> <div>This part is legit</div> </body> </html> </html-escaper> </div> <template id="html-escaper"> <code v-escape-content> <slot> </slot> </code> </template> 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM