Vue 批量注册局部组件及应用

博客地址:https://ainyi.com/105

批量注册路由的有个博客说到:https://ainyi.com/77

实际工作中,可能会遇到一个大页面里面有很多个模块,这些模块一般是需要拆分到单独的组件中,然后父组件再引入

我最近就遇到一个可以拆分成 10 个模块的大表单页面,拆分成局部组件后还是得一个个导入、声明,最后在 template 应用。作为一个程序员,我们怎么能写这么一大段重复的代码呢啊哈哈哈哈

所以就来搞搞局部组件批量注册批量应用

WechatIMG29.png

如图,一个 Index.vue 文件中需要引入 modules 里面 10 个子组件

注册

先扫描读取目录下每个文件,如有需要过滤的组件标出,再批量注册

const requireComponent = require.context('./modules', false, /w+.(vue|js)$/)

const cmps = {}
// 这里我把 CreateHeader 组件排除,单独引入
const filterCmps = ['./CreateHeader.vue']

requireComponent.keys().forEach(fileName => {
  let cmp = requireComponent(fileName).default
  !filterCmps.includes(fileName) && (cmps[cmp.name] = cmp)
})
export default {
  components: {
    createHeader: () => import('./modules/CreateHeader'),
    ...cmps
  },
  data() {
    return {
      // 这里做排序处理,按原型图可拆分的模块顺序,将每个组件的 name 命名为 xxx_${index}
      // 为什么做排序?为了循环依次应用子组件
      componentList: Object.keys(cmps).sort(
        (a, b) => a.split('_')[1] - b.split('_')[1]
      )
    }
  }
}

应用

template 应用手写每个组件也几乎不可能了,太多了
上面 componentList 做了排序处理,按照原型图的顺序命名组件的 name: xxx_${index}
有顺序了,这里就可以使用 component、is 依次用 v-for 循环应用

如果每个组件的位置不是排列在一起的(中间穿插其它内容),那就单独一个个写吧,也不用做排序

<template>
  <div class="krry-appointment">
    <create-header :active="active" :translate="translate"></create-header>
    <div class="form-content">
      <component
        v-for="ele in componentList"
        :dataSource="dataSource"
        :key="ele"
        :is="ele"
      ></component>
    </div>
  </div>
</template>

这样就大功告成,是不是简化了很多代码~


温馨提示:如果在上面 v-for 循环的 component 定义 ref,那么此 $refs 将会是一个数组

<component
  ref="formModules"
  v-for="ele in componentList"
  :dataSource="dataSource"
  :key="ele"
  :is="ele"
></component>
this.$refs.formModules.forEach(ele => {
  // TODO
  // 处理每个子组件(ele)
})

博客地址:https://ainyi.com/105

原文地址:https://www.cnblogs.com/ainyi/p/14722182.html