Vue.js中如何设置必填Slot?从Prop传HTML场景迁移疑问
Nice call switching from a prop to a slot for your rich text alert content — that’s way more intuitive for this use case! Let me break down why this works better, and make sure you’ve got all the pieces set up correctly:
- Rich text readability: Nesting
<strong>bazboo</strong>directly in a slot is far easier to read and maintain than passing it as an HTML string in a prop. You also avoid messy string escaping issues. - Flexible content structure: If you later need to add more elements to the alert (like icons, buttons, or multi-line text), slots let you extend the content without modifying prop definitions or juggling complex string concatenation.
- Cleaner dynamic content handling: For server-provided HTML (your original use case), slots pair seamlessly with Vue’s
v-htmldirective to render dynamic content safely (more on that below).
Component Setup (Vue 2/3)
First, update your foobar component to remove the old prop and define a default slot:
<template> <div class="alert-container"> <!-- Default slot to accept content from parent --> <slot></slot> </div> </template> <script> export default { props: { // Remove the old alertContent prop entirely } } </script>
Parent Component Usage
Static Rich Text
For static content like your example, just pass the HTML directly inside the component tag:
<foobar> <strong>bazboo</strong> </foobar>
Dynamic Server-Sent HTML
If you’re still pulling content from a server (your original scenario), use v-html inside the slot to render the raw HTML string:
<foobar> <div v-html="serverAlertContent"></div> </foobar>
Important: If the server content isn’t fully trusted, use a sanitization library to strip malicious code before rendering with
v-htmlto avoid XSS risks.
Extra Optimizations
- Add fallback content: Give the slot a default message in case the parent doesn’t pass any content:
<template> <div class="alert-container"> <slot>No alert content provided</slot> </div> </template>
- Named slots for complex alerts: If you need separate sections (like a title and body), use named slots for better organization:
<!-- foobar component template --> <template> <div class="alert-container"> <slot name="title">Default Alert Title</slot> <slot name="body"></slot> </div> </template> <!-- Parent component usage --> <foobar> <template #title> <h3>Important Notice</h3> </template> <template #body> <strong>bazboo</strong> - This is critical info! </template> </foobar>
内容的提问来源于stack exchange,提问作者Goose

