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

Vue2中如何在JSX语法里使用v-html指令?

Vue 2 JSX 中实现 v-html 效果的方法

Hey there! In Vue 2's JSX syntax, we don’t have the direct v-html directive you’re used to in template files, but achieving the exact same functionality is super straightforward.

核心实现方式

Instead of using v-html, you’ll use the domPropsInnerHTML attribute (or the domProps object syntax) in your JSX to bind raw HTML content to an element. This maps directly to the native DOM innerHTML property, just like how v-html works under the hood.

示例 1:普通组件的 Render 函数

Here’s how you’d implement this in a regular Vue component with a JSX render function:

export default {
  props: {
    safeHtmlContent: {
      type: String,
      required: true
    }
  },
  render() {
    // 两种写法都可行,选你习惯的一种
    return (
      // 写法1:直接使用 domPropsInnerHTML 属性
      <div domPropsInnerHTML={this.safeHtmlContent} />

      // 写法2:通过 domProps 对象传递
      // <div domProps={{ innerHTML: this.safeHtmlContent }} />
    )
  }
}

示例 2:函数式组件

If you’re working with a functional component, the approach is almost identical—you just pull the prop from the context:

const HtmlRenderComponent = {
  functional: true,
  props: {
    content: {
      type: String,
      required: true
    }
  },
  render(h, context) {
    return <span domPropsInnerHTML={context.props.content} />
  }
}

重要注意事项

Just like with v-html, you must ensure the HTML content you’re rendering is safe and trusted. Never render unfiltered user input directly—this exposes your app to XSS vulnerabilities. Always sanitize user-provided HTML before using it here.

内容的提问来源于stack exchange,提问作者Andrey Ponomarenko

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.25 08:21:29