vue如何动态的引入组件

我想实现通过后台数据来引用不同的组件,比如我拿到了id为1的数据,我就想引用我写好的1.vue文件,因为有可能有上千个这种文件,我需要后台的数据来定位是哪一个文件,请问这种该怎么解决呀

阅读 20.9k
8 个回答

这个是我的解决方案
不知道是不是比较通用或者正确的解决方案, 用render函数去判断要渲染哪个标签

//run.vue
// homeComponents 是异步组件列表.
    import homeComponents from '@/assets/js/homeComponents';

    export default {
        render: function(cElement, context) {
            return cElement(homeComponents[this.temp.type], {
                props: {
                    temp: this.temp,// 组件数据
                }
            })
        },
        props: {
            temp: {
                type: Object,
                required: true,
                default: {}
            },
        }

// home.vue
// 只要注册这个 run 组件, 然后传入 temp , 根据temp.type, 去渲染相应的 component
// 这样你只要在页面上写一个run组件, 传入 type, 就会异步加载你需要的组件
<template>
    <run v-for="node in element" :temp="node" :key="node.fieldId" />
</template>

其实就是实现了官网里的 component 标签的功能. 感觉这样更灵活吧

<component :is="你的组件名"></component>

提供一种方法或者思路

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>

也可以这样,先引入组件,用v-if,显示满足条件的组件,当然如果组件多的话,会麻烦些

同一个模板的话,直接改变参数就行了。不同模板的话,不可能有成千上万个,你说的因该叫路由了

楼主解决了吗 遇到了同样的问题

新手上路,请多包涵

我的解决方案
话不多 直接代码

<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>
撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题