Vue中如何在渲染前解析替换HTML字符串内的{{}}插值变量
结论
- Vue 没有内置可直接用于
v-html解析{{}}模板插值的方法。v-html设计上仅会将传入内容作为普通HTML插入,不会执行任何Vue模板编译逻辑,以此降低XSS安全风险。 - 可以根据需求复杂度选择以下两种自定义实现方案:
方案1:轻量变量替换(仅处理{{}}插值,无其他模板语法)
适合仅需要替换占位符、不需要处理Vue指令/组件的场景,通过正则匹配占位符后从当前上下文取值替换即可:
// 变量取值工具,支持嵌套变量如 {{a.b.c}} const getNestedValue = (context, path) => { return path.trim().split('.').reduce((res, key) => res?.[key], context) } // 解析方法 const parseTemplate = (str, context) => { return str.replace(/{{\s*(.+?)\s*}}/g, (match, path) => { return getNestedValue(context, path) ?? match }) }
模板中使用示例:
<template> <div v-html="parseTemplate(desc, {aVar})"></div> </template> <script setup> const aVar = '实际变量值' const desc = "<p>Some text {{aVar}}</p>" // 上面的parseTemplate方法定义在这里 </script>
方案2:完整模板编译(支持所有Vue模板语法)
如果需要在字符串模板中使用v-if、v-for甚至自定义组件等完整Vue能力,可以使用Vue提供的compile方法手动编译模板:
注意:该方案需要你使用的Vue版本带编译器,Vue2/Vue3 CLI创建的项目默认是运行时版本,需要在vue.config.js中开启
runtimeCompiler: true配置才能使用。同时该方案存在XSS风险,仅可用于完全可信的模板字符串场景,不可用于包含用户输入的内容。
<template> <DynamicTpl :tplStr="desc" :ctx="{aVar}" /> </template> <script setup> import { defineComponent, compile } from 'vue' const aVar = '实际变量值' const desc = "<p>Some text {{aVar}}</p>" // 定义动态模板组件 const DynamicTpl = defineComponent({ props: ['tplStr', 'ctx'], setup(props) { const render = compile(props.tplStr) return () => render(props.ctx) } }) </script>
内容的提问来源于stack exchange,提问作者orbitory
相关产品推荐
相关产品推荐

