This is the second day of my participation in the August Text Challenge.More challenges in August
We are familiar with the V-HTML directive. If you have read back to the Vue3 directive (1), you can do something similar. If not, let’s read on.
How to use
The V-HTML directive is used to update the innerHTML of an element. Note: Content is inserted as normal HTML – not compiled as a Vue template. Insert your HTML code into the element where the current directive is located.
Use the V-HTML directive directly as follows:
// data {HTML :"<span>hello world</span>"} // use<h1 v-html="html"></h1>// The compiled result<h1>
<span>hello world</span>
</h1>
Copy the code
V-html is no doubt used much less often than V-text in project development (it varies from person to person, but there are fewer scenarios in which v-HTML is used), so what scenarios do we use it in? Feel free to comment on the scenarios you use, and here are the ones I think you can use.
- For special purposes, the data from the back end is an HTML string and needs to be rendered
- When using a table, we sometimes need an item to be displayed in a different color or style, so we can insert an inline style tag
- To display multiple tags under one tag, use the V-HTML directive
- . (Waiting for your comment)
Custom instruction
How to customize an instruction in Vue3?
In the last article we simulated a V-text directive. Today we will simulate a V-HTML directive. Let’s just call it V-CHTML.
<div id="app">
<h1 v-chtml="html"></h1>
</div>
<script src=".. /dist/vue.global.js"></script>
<script>
const { createApp, ref } = Vue
const app = createApp({
setup() {
const html=ref("<span style='color:red'>hello world</span>")
return {
html
}
}
})
// Custom V-chTML changes the content of the current element
app.directive('chtml', {mounted(el,{value}){
el.innerHTML=value;
}
})
app.mount("#app")
</script>
Copy the code
If you read back to Vue3, you can see that custom v-chtml is basically the same as v-ctext, with minor differences.
innerHTML
As you can see from el.innerhtml =value in the code above, we use innerHTML to replace the contents of el. The specified value is parsed to HTML or XML (based on the document type), resulting in a DocumentFragment object representing a new DOM node set for the new element.
conclusion
-
Official tip: Rendering arbitrary HTML dynamically on a website is very dangerous, as it is prone to XSS attacks. Use V-HTML only for trusted content, never for user-submitted content.
-
V-html has a lot in common with V-text, and the essence of what they do is change the content of the current element.
For more articles, the portal has opened: Look back at the Vue3 catalogue!