You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Vue插值字符串时如何使用组件?解决标签转义与组件替换问题

How to Pass Mixed Text and Components to a Vue Component Without Escaping

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-html instead 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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.27 06:34:00