Welcome toVigges Developer Community-Open, Learning,Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
1.9k views
in Technique[技术] by (71.8m points)

vue如何在安装的依赖中导入项目中的组件?

我现在vue项目A中有一个这样的功能,根据后台返回的组件路径动态显示对应的组件,代码如下:
Layout.vue

<template>
    <template v-for=(item,index) in layouts :key="index">
        <component :is="item.view"></component>
    </template>
</template>
export default{
    name:'Layout',
    data(){
        return {
            layouts:[]
        }
    },
    methods:{
        getData(){
            //查询方法
            queryDashboardItem(query).then(res => {
                if (res.data.success) {
                    let rows = res.data.rows;
                    rows.forEach(item => {
                        // item.componentPath 的值类似于 components/base/demo/DemoTest.vue 以components目录开头的字符串
                        import(`@/${item.componentPath}`).then(cm=>{
                            item.view = cm.default;
                            this.layouts.push(item);
                        })
                    })
                } else {
                    this.$message.error(res.data.message)
                }
            }).catch(e => {
                console.log(e)
            })
        }
    },
    mounted(){
        this.getData();
    }
}

现在我将项目A构建成库(假设此库名就叫layout)并发布到npm上。然后我再项目B中安装此依赖并使用该依赖中的Layout功能。发现无法使用,无法使用的原因是安装的依赖在 node_modules 文件夹中。但此时动态导入的组件在B项目中,导致无法根据接口返回的路径正确的找到对应的组件。这种情况改如何处理?

一句话概括就是想在安装的依赖(这个依赖是自己开发的)中引入项目上的组件。


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

建议换个思路吧, 不要使用后端返回动态路径的方式,
本地组件都使用常规的静态导入,每个组件取个标识名,后端返回标识名用来区分判断。

具体的说就是:
定义一个中转组件,在这个中转组件里引入所有需要的子组件,全部用v-if通过判断标识名来控制展示,
然后在你的这个Layout.vue里引入这个中转组件,遍历循环,传入后端返回的标识名,就能实现了。
中转组件comps.vue示例:

<template>
 <comp1 v-if="type='comp1'"/>
 <comp2 v-if="type='comp2'"/>
 <comp3 v-if="type='comp3'"/>
 ...
</template>
<script>
 props: ['type']
</script>

引用方式示例:

<template>
  <template v-for=(item,index) in layouts :key="index">
    <comps :type="item.type"/>
  </template>
</template>

(即使真的不得不用动态,那也是用dom动态,利用v-html或者jsx实现,而不是考虑组件路径动态)


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to Vigges Developer Community for programmer and developer-Open, Learning and Share
...