require动态引入

文章展示了如何在Vue.js中使用`require`动态引入组件,特别是在组件不确定或需动态切换的情况下。通过`component`标签结合`is`属性,以及`onTabClick`方法处理组件切换。同时,文章提到了动态引入可能带来的问题,如异步加载、编译阶段的被动编译等,并建议组件提供统一接口以简化操作。
摘要由CSDN通过智能技术生成

1.require动态引入

1.背景

(1)组件不确定
(2)多个组件结合component标签动态切换

2.应用demo

<article>
    <component ref="asyncComp" :is="compName"></component>
</article>

onTabClick(item) {
  this.currentTab = item;
  require(['@views/dashboard/components/' + item.path + '.vue'], (res) => {
    this.compName = res.default;
    this.$nextTick(() => {
      this.$refs.asyncComp.edit({
        factoryId: this.queryParam.factoryId
      })
    })
  })
}

// 结合弹窗,基础modal
<template>
  <a-modal
	class="BaseModal"
	:width="width"
	style="min-width: 800px"
	:visible="visible"
	:okButtonProps="{ props: {disabled: disableSubmit} }"
	:confirmLoading="confirmLoading"
	:footer="footer"
	@ok="handleOk"
	@cancel="handleCancel"
	cancelText="关闭">
	<template slot="title">
	  <div style="height: 25px">
		{{name}}
	  </div>
	</template>
	<a-spin :spinning="spinning">
	  <component ref="comp" :key="compName" :is="compName" @ok="handleCancel"></component>
	</a-spin>
  </a-modal>
</template>

<script>
const ModalBaseAttr = {
  width: 900,
  visible: false,
  confirmLoading: false,
  loading: false,
  disableSubmit: false,
  videoSource: [],
  footer: false,
  labelCol: {
	xs: { span: 24 },
	sm: { span: 6 },
  },
  wrapperCol: {
	xs: { span: 24 },
	sm: { span: 16 },
  },
  dayFormat: 'YYYY-MM-DD',
  monthFormat: 'YYYY-MM',
  spinning: false,
  url: {
	list: '/video/tVideo/list'
  }
}

export default {
  name: 'BaseModal',
  props: {
	infoId: {
	  type: String,
	  default: ''
	}
  },
  data() {
	return {
	  compName: '',
	  ...ModalBaseAttr,
	  width: '70%',
	  name: '',
	  url: {
		add: 'equipment/equipmentTvideo/add',
		list: '/video/tVideo/list'
	  },
	  videoSource: [],
	  model: {}
	};
  },
  methods: {
	add() {
	  this.edit({})
	},
	edit(type) {
	// title: type.name,
    // compName: 'AnalysisUserList',
    // footer: false,
	  Object.assign(this, type)
	  this.$nextTick(() => {
		this.visible = true;
		this.$nextTick(() => {
		  this.$refs.comp.edit && this.$refs.comp.edit(type.record)
		})
	  })
	},
	handleOk() {
	  this.$refs.comp.handleOk();
	},
	handleCancel() {
	  this.visible = false
	}
  }
};
</script>

<style scoped lang="less">
.BaseModal {

}
</style>

3.注意点

(1)无论是import还是require都是异步的
(2)建议组件提供统一的入口,例如edit()
(3)在编译阶段,被动编译引入目录下的所有文件(@views/dashboard/components/),即使没有使用
(4)初始目录不确定下无法动态引入

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值