Performance: Sanitizing user input
Sanitizing user input affects page security and rendering stability by preventing injection attacks and layout shifts caused by malicious or malformed input.
import DOMPurify from 'dompurify'; const userInput = '<img src=x onerror=alert(1)>Hello'; const safeInput = DOMPurify.sanitize(userInput); <template> <div v-html="safeInput"></div> </template>
const userInput = '<img src=x onerror=alert(1)>Hello'; // Directly binding with v-html <template> <div v-html="userInput"></div> </template>
| Pattern | DOM Operations | Reflows | Paint Cost | Verdict |
|---|---|---|---|---|
| Direct v-html with unsanitized input | Adds unpredictable nodes and event handlers | Multiple reflows if images/scripts load or fail | High paint cost due to layout shifts | [X] Bad |
| v-html with sanitized input (e.g., DOMPurify) | Adds only safe nodes, no scripts | Single reflow on initial render | Low paint cost, stable layout | [OK] Good |
v-model directive binds input values to data reactively.v-model fits sanitizingv-model, you can watch and sanitize input as it changes.cleanInput after typing ""? <template>
<input v-model="userInput" @input="sanitizeInput" />
</template>
<script setup>
import { ref } from 'vue'
const userInput = ref('')
const cleanInput = ref('')
function sanitizeInput() {
cleanInput.value = userInput.value.replace(/<.*?>/g, '')
}
</script>/<.*?>/g matches any text between < and > including the tags.function sanitizeInput() {
cleanInput.value = userInput.value.replace(/<.*>/g, '')
}/<.*>/g is greedy and matches from the first < to the last > in the string.function sanitizeInput() {
cleanInput.value = userInput.value.replace(_____, '')
}/[^a-zA-Z ]/g matches any character NOT a letter or space, so replacing these removes unwanted characters.Pass the test and this pattern moves unknown