Vue插值字符串时如何使用组件?解决标签转义与组件替换问题
Hey there! Let's break down how to fix this issue. The core problem here is two-fold:
- Vue's
{{ }}interpolation automatically escapes HTML content to prevent XSS attacks, so your<component-B/>string gets converted to plain text instead of being parsed. - Even if the HTML wasn't escaped, Vue won't turn a string into a functional component instance on its own.
The proper Vue-native solution for this scenario is using slots—this is exactly what slots were designed for! Here's how to adjust your code:
Step 1: Refactor Component-A to Use a Slot
Instead of relying on a prop to receive content, rewrite Component-A to accept a slot for dynamic content:
<template> <div> <!-- Replace {{someProp}} with a slot to accept external content --> <slot></slot> </div> </template>
Step 2: Pass Content Directly in the Parent Component
Now when you use Component-A in another component, you can directly place your text and Component-B inside the Component-A tags—no props required:
<component-A> Some text and <component-B/> </component-A>
Why This Works
Slots are Vue's built-in mechanism for content distribution. They automatically render any content (text, components, raw HTML) you pass into the parent component's tags, without escaping, and properly instantiate any child components included. This aligns perfectly with Vue's component design principles.
What If You Really Need to Use a Prop?
If for some edge case you must use a prop (note: this is not recommended for component content), keep these limitations in mind:
- Using
v-htmlinstead of{{ }}would render raw HTML, but it cannot parse Vue components—<component-B/>would still show up as plain text. - To make a prop work with components, you'd have to pass a render function or component definition and use dynamic components, which adds unnecessary complexity compared to using slots.
Stick with slots—they're the cleanest, most idiomatic solution here!
内容的提问来源于stack exchange,提问作者Dmitry Lozhkin

