Vue动态加载巨量模板组件

对于一些特殊的软件系统会涉及大量模板,比如不同的设备采集原始数据的页面,如果存在成千种类的设备,那么对应原始数据采集模板页面也会有上千个, 对于普通的vue文件import上千个modules是不可想象的,下面介绍一个利用循环语句加载模板的方法。

<template>
  <div id="example">
    <input v-model="pointedView" type="text" />
    <button @click="change">切换页面</button>
    <component :is="currentView"></component>
  </div>
</template>

<script>
import Vue from 'vue'
import upperFirst from 'lodash/upperFirst'
import camelCase from 'lodash/camelCase'

const requireComponent = require.context(
  '@/components/children',
  false,
  /\.(vue|js)$/
)
requireComponent.keys().forEach(fileName => {
  const componentConfig = requireComponent(fileName)
  const componentName = upperFirst(
    camelCase(
      fileName
        .split('/')
        .pop()
        .replace(/\.\w+$/, '')
    )
  )
  Vue.component(
    componentName,
    componentConfig.default || componentConfig
  )
})
export default {
  name: 'example',
  data: function () {
    return {
      pointedView: '',
      currentView: ''
    }
  },
  methods: {
    change () {
      this.currentView = this.pointedView
    }
  }
}
</script>

相应在components/children下添加模板compontent1, compontent2, compontent3...

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值