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

Vue3:注入模板组件如何编译自定义输入变量并输出?

Vue组件模板变量编译方案(基于provide/inject)

需求与问题

  • 需求:实现一个可注入模板的组件,模板中的变量需通过provide/inject传递的变量进行编译替换。
  • 问题:补全自定义组件中???标记的代码,达成预期输出,也接受其他可行实现方式。

补充说明

  • PS1:采用provide/inject是因为实际项目中组件层级较深,此处为简化示例做了精简。
  • PS2:input_data来自用户输入。
  • PS3:支持多个变量的替换。

应用示例

<parent :input_data="{full_url:'{{base_url}}/some/path/here', variables:[{key:'base_url','value':'http://test.com'}]}"></parent>

父组件代码

<script>
import Custom from './Custom.vue'
import { computed } from 'vue'
export default {
  name: 'parent',
  props: ['input_data'],
  provide: () => ({
    variables: computed(() => {
        let variables = {}
        for (let v of this.input_data.variables) {
            variables[v.key] = v.value
        }
        return variables;
    })
  })
}
</script>
<template>
  <custom :template="input_data.full_url"></custom>
</template>

自定义组件待完善代码

export default {
  inject: ['variables'],
  props: {
    template: {
      required: true,
      type: String,
    },
  },
  // ???
  render(){
    return this.template
  }
}

预期输出

<div><!-- app -->
  <div><!-- parent -->
    <div><!-- custom component -->
      http://test.com/some/path/here
    </div>
  </div>
</div>

解决方案

实现思路

通过计算属性监听variables和template的变化,将模板中{{变量名}}格式的占位符替换为provide传入的对应值。

修改后的自定义组件代码

export default {
  inject: ['variables'],
  props: {
    template: {
      required: true,
      type: String,
    },
  },
  computed: {
    compiledTemplate() {
      let compiled = this.template;
      Object.entries(this.variables).forEach(([key, value]) => {
        // 全局匹配{{key}}格式的占位符并替换
        const placeholder = new RegExp(`{{${key}}}`, 'g');
        compiled = compiled.replace(placeholder, value);
      });
      return compiled;
    }
  },
  render(){
    return this.compiledTemplate
  }
}

方案说明

  1. 响应式更新:利用计算属性compiledTemplate,当variables或template发生变化时自动重新编译模板。
  2. 多变量支持:通过Object.entries遍历所有传递的变量,实现批量替换。
  3. 轻量高效:针对简单变量替换场景,该方案无需引入额外编译工具,性能开销低。

如果需要处理更复杂的模板逻辑(如条件判断、循环),可以使用Vue内置的compile函数动态编译渲染函数,但会增加一定的性能成本,需根据实际需求选择。


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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.15 03:02:05