解决vue打包后动态组件component加载字符串模板失效问题

今天在部署vue项目的时候,发现动态模板加载的图片无法显示

以下是我代码里面失效部分

<template>
  <component :is="component_prop.type" :prop_data="component_prop" />
</template>
<script>
let importComponents = {}
export default {
  components: importComponents,
  provide: {},
  props: ['svgInfoData', 'component_prop'],
  data() {
    return {}
  },
  created() {
    this.svgInfoData.forEach((f) => {
      let componentInfo = {
        template: f.template,
        props: f.props
      }
      importComponents[f.type] = componentInfo
    })
  },
  methods: {}
}
</script>

经过一顿查疑解惑,终于找到了问题所在

1.首先这个问题和创建vue项目的时候选择编译模式有关

vue有runtime-compiler和runtime-only两种编译模式,默认为runtime-only,这种模式下的代码轻便,但是不能使用template参数,

如果使用vue-cli进行项目搭建,可以在vue.config.js里面配置属性runtimeCompiler: true

module.exports = {
    runtimeCompiler: true // 运行时编译
}

如果使用vite搭建的项目,则修改vite.config.js 里面的alias属性:

resolve:{
    alias:[
        {
            find: 'vue',
            replacement: 'vue/dist/vue.esm-bundler.js',
        },
    ],
},

然后重新打包发布就可以了

参考文章:

https://blog.csdn.net/Heixiu6/article/details/126714616

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
Vue3中,可以使用 `v-bind` 指令的 `.sync` 修饰符来实现父组件与子组件之间的双向绑定,从而获取子组件实例并调用子组件的方法。 首先,需要在父组件中使用 `v-bind` 指令将子组件的实例绑定到父组件的一个变量上。例如: ```vue <template> <div> <component :is="selectedComponent" :child-instance.sync="childInstance"></component> <button @click="handleClick">Call Child's Method</button> </div> </template> <script> import ChildComponent1 from './ChildComponent1.vue' import ChildComponent2 from './ChildComponent2.vue' export default { components: { ChildComponent1, ChildComponent2 }, data() { return { selectedComponent: 'ChildComponent1', childInstance: null } }, methods: { handleClick() { if (this.childInstance) { this.childInstance.doSomething() } } } } </script> ``` 在子组件中,需要使用 `emit` 方法将子组件的实例暴露给父组件。例如: ```vue <template> <div> <p>{{ message }}</p> </div> </template> <script> export default { data() { return { message: 'Hello from ChildComponent1!' } }, mounted() { this.$emit('update:childInstance', this) }, methods: { doSomething() { console.log('ChildComponent1 is doing something...') } } } </script> ``` 这样,父组件就可以在 `childInstance` 变量中获取到子组件的实例,并调用子组件的方法。需要注意的是,这种方式只适用于动态组件,即使用 `v-bind` 指令的 `is` 属性来动态切换组件。如果是静态组件,可以直接通过 `ref` 获取子组件实例。
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值