Performance: XSS prevention in templates
This affects page security and rendering speed by controlling how user input is handled and displayed in templates.
<template>
<div>{{ userInput }}</div>
</template>
<script setup>
const userInput = '<img src=x onerror=alert(1)>'
</script><template> <div v-html="userInput"></div> </template> <script setup> const userInput = '<img src=x onerror=alert(1)>' </script>
| Pattern | DOM Operations | Reflows | Paint Cost | Verdict |
|---|---|---|---|---|
| Using v-html with untrusted input | Adds nodes dynamically | Triggers multiple reflows if scripts modify layout | High due to repaints and possible script execution | [X] Bad |
| Using {{ }} interpolation for user input | No extra nodes, text only | No reflows caused by script injection | Low paint cost, stable layout | [OK] Good |
{{ }} to prevent XSS by converting special characters to safe HTML entities.v-html inserts raw HTML and can cause XSS if content is unsafe. Direct DOM manipulation bypasses Vue's protections.<div>{{ userInput }}</div> uses correct Vue syntax with double curly braces and quotes are properly placed.<div>{{ userInput }}</div> escapes content automatically, making it safe. <div v-html="userInput"></div> uses v-html which inserts raw HTML and can be unsafe. <div v-text=userInput></div> misses quotes around the binding value, causing syntax error. <div>{{ userInput</div> }} has mismatched braces causing syntax error.userInput is '<img src=x onerror=alert(1)>', what will be rendered in the browser?<img> tag runs and triggers the alert.<div v-html="userContent"></div>
<b> and <i> but prevent XSS in Vue. Which approach is best?<b> and <i>.Pass the test and this pattern moves unknown