我想实现通过后台数据来引用不同的组件,比如我拿到了id为1的数据,我就想引用我写好的1.vue文件,因为有可能有上千个这种文件,我需要后台的数据来定位是哪一个文件,请问这种该怎么解决呀
我想实现通过后台数据来引用不同的组件,比如我拿到了id为1的数据,我就想引用我写好的1.vue文件,因为有可能有上千个这种文件,我需要后台的数据来定位是哪一个文件,请问这种该怎么解决呀
提供一种方法或者思路
1.首先用template或者script标签封装模板
<template id="com1">
<div>组件1</div>
</template>
<template id="com2">
<div>组件2</div>
</template>
2.构建组件
var com1 = Vue.extend({
template:'#com1'
});
var com2 = Vue.extend({
template:'#com2'
});
3.注册组件
components:{com1,com2}
4.根据数据创建一个组件列表
/*请求数据回调函数*/
var _this = this
function(res){
if(res.id == 1){
_this.comList.push('com1')
}
if(res.id == 2){
_this.comList.push('com2')
}
}
5.动态引入组件
<div v-for="d in comList">
<component :is="d"></component>
</div>
回答都到了一个误区,提问题的同学是说自己有100个组件,都要一次 import 进来吗 ?
https://www.cnblogs.com/jun-qi/p/10931205.html
我的解决方案
话不多 直接代码
<template>
<a-card>
<a-row v-for="(row,rowIdx) in rowPieces" :key="rowIdx">
<a-col v-for="(col,colIdx) in row" :key="colIdx" :span="col.span">
<component :is="col.drawItem"/>
</a-col>
</a-row>
</a-card>
</template>
<script>
import { getAction, postAction } from '@/api/manage'
export default {
name: 'portal',
data () {
return {
configList: [],
rowPieces:[],
url: {
userRole: 'sys/user/getUserRoleInfo',
// listPieces: 'portal/portalPiece/listByOrg',
listConfig: '/portal/portalConfig/listByOrgAndUser'
}
}
},
activated () {
this.loadConfig()
},
mounted () {
this.loadConfig()
},
watch:{
configList(configList){
let res = [];
let configObj = JSON.parse(JSON.stringify(configList))
for (let key in configObj) {
res.push(configObj[key].map(c=>{
c.drawItem = this.loadPiece(c.path)
return c
}))
}
this.rowPieces = res
}
},
methods: {
loadPiece(path){
return ()=> import('@views/' + path )
},
notFoundPiece(){
return ()=> import('@views/portal/NoVueFound' )
},
async loadConfig () {
let orgId = this.$store.state.app.orgId
let userId = this.$store.getters.userInfo.id
let rolesRes = await getAction(this.url.userRole, { userId })
let effectRole = rolesRes.result ? rolesRes.result[0] : null
let roleId = effectRole ? effectRole.id : ''
let configRes = await postAction(this.url.listConfig, { roleId, orgId })
let sourceCfgs=configRes.result.records.map(c=>{
let config = _.pick(c,['rowIndex','colIndex','span'])
config.pieceName = c.portalPiece.portalPiece
config.path = c.portalPiece.path
return Object.assign({},config)
})
this.configList = _.groupBy(sourceCfgs,'rowIndex')
}
}
}
</script>
<style scoped>
</style>
10 回答11.1k 阅读
6 回答3k 阅读
5 回答4.8k 阅读✓ 已解决
4 回答3.1k 阅读✓ 已解决
2 回答2.7k 阅读✓ 已解决
2 回答4.7k 阅读✓ 已解决
4 回答4.3k 阅读✓ 已解决
这个是我的解决方案
不知道是不是比较通用或者正确的解决方案, 用render函数去判断要渲染哪个标签
其实就是实现了官网里的
component
标签的功能. 感觉这样更灵活吧