Consider a Vue 3 component that sanitizes user input before displaying it. The user types <script>alert('Hi')</script> in the input box. Which option correctly shows the sanitized output in the rendered page?
<template>
<div>
<input v-model="userInput" placeholder="Type here" />
<p v-html="sanitizedInput"></p>
</div>
</template>
<script setup>
import { ref, computed } from 'vue'
import DOMPurify from 'dompurify'
const userInput = ref('')
const sanitizedInput = computed(() => DOMPurify.sanitize(userInput.value))
</script>Think about how DOMPurify changes dangerous HTML tags to safe text.
DOMPurify converts dangerous tags like <script> into safe text entities so they display as text, not executed code. This prevents scripts from running.
Given a user input stored in userInput, which option correctly uses DOMPurify to sanitize and render it safely in Vue 3?
Remember that v-html renders HTML, but you must sanitize it first.
Option B uses v-html with sanitized input, so HTML tags are safely rendered. Option B escapes HTML and shows tags as text. Option B also escapes HTML. Option B renders raw HTML without sanitizing, which is unsafe.
Look at this Vue 3 component code:
<template>
<div>
<input v-model="userInput" />
<p v-html="userInput"></p>
</div>
</template>
<script setup>
import { ref } from 'vue'
const userInput = ref('')
</script>Why can a user still run scripts by typing HTML with <script> tags?
Think about what v-html does with raw HTML strings.
Using v-html with unsanitized user input allows scripts to run. Vue does not sanitize automatically. You must sanitize input before binding it to v-html.
Why do developers sanitize user input before rendering it in Vue components?
Think about security risks from user input.
Sanitizing input removes harmful scripts that attackers might inject, protecting users from XSS attacks. It is a key security practice.
displayText after input changes?In this Vue 3 component, what will displayText contain after the user types <b>Hello</b>?
<template>
<div>
<input v-model="userInput" />
<p v-html="displayText"></p>
</div>
</template>
<script setup>
import { ref, computed } from 'vue'
import DOMPurify from 'dompurify'
const userInput = ref('')
const displayText = computed(() => {
const dirty = userInput.value
return DOMPurify.sanitize(dirty, { ALLOWED_TAGS: ['b'] })
})
</script>Check which tags are allowed by DOMPurify in this config.
DOMPurify is configured to allow only b tags, so the <b>Hello</b> input keeps the bold tags and removes others.