文章目錄
- 一、使用場景
- 二、使用步驟
-
- 1.檔案目錄
- 2.HTML代碼
- 3.js代碼
- 4.css代碼(可不看,寫出來隻是為了代碼完整性,拿來可以直接運作展示)
- 三、總結
一、使用場景
在日常開發中,經常會有這樣一種情況:
import A from 'components/A'
import B from 'components/B'
import C from 'components/C'
import D from 'components/D'
遇到這種重複的代碼,就在想,是否可以進行以下優化,一次性全部引入。于是就找到了
webpack
的
api
,通過調用
require.context
來進行處理,具體代碼如下:
二、使用步驟
涉及到:
- 元件名稱為帶中橫線規範,最後要轉為駝峰命名法的功能;
-
的component
屬性;is
具體詳解都在代碼中:
1.檔案目錄
2.HTML代碼
<template>
<div class="water-analysis">
<div class="content-box" ref="contentbox">
<a-tabs :default-active-key="activeComponent" @change="tabChangeHandle">
<a-tab-pane
v-for="item in tabList"
:key="item.key"
:tab="item.tab"
></a-tab-pane>
</a-tabs>
<div class="tab-pane-box">
<!-- 通過is屬性,綁定對應的元件名稱,展示對應的元件 -->
<component :is="activeComponent"></component>
</div>
</div>
</div>
</template>
3.js代碼
文法:
require.context(directory, useSubdirectories, regExp)
-
: 要查找的檔案路徑directory
-
: 是否查找子目錄useSubdirectories
-
: 要比對檔案的正則regExp
傳回值:兩個方法一個屬性
-
: 傳回比對成功子產品的名字組成的數組keys()
-
: 接受一個參數request,request為test檔案夾下面比對檔案的相對路徑,傳回這個比對檔案相對于整個工程的相對路徑resolve()
-
:執行環境的id,傳回的是一個字元串,主要用在id
,應該是熱加載module.hot.accept
<script>
// 中橫線轉駝峰
var camelCase = function (s) {
return s.replace(/-\w/g, function (x) {
return x.slice(1).toUpperCase();
});
};
// 批量引入子元件 重點,文法見上
const allComponents = require.context("./comp", false, /\.vue$/);
console.log(allComponents.keys())
// ["./tem-a.vue", "./tem-b.vue", "./tem-c.vue", "./tem-d.vue"]
console.log(allComponents.id)
//./src/views/tempManage/comp sync \.vue$
//制作元件數組,在下方components中注冊使用
let resComponents = {};
allComponents.keys().forEach(comName => {
let name = camelCase(comName);
const comp = allComponents(comName);
resComponents[name.replace(/^\.\/(.*)\.\w+$/, "$1")] = comp.default;
});
export default {
name: "WaterQuery",
components: resComponents,
data() {
return {
activeComponent: "temA",
tabList: [
{
key: "temA",
tab: "A元件",
},
{
key: "temB",
tab: "B元件",
},
{
key: "temC",
tab: "C元件",
},
{
key: "temD",
tab: "D元件",
},
],
};
},
created() {
if (this.$route.query["val"]) {
this.activeComponent = this.$route.query["val"];
}
},
methods: {
// 切換tab欄
tabChangeHandle(val) {
const {path} = this.$router;
this.$router.push({
path,
query: {val},
});
this.activeComponent = val;
},
},
};
</script>
4.css代碼(可不看,寫出來隻是為了代碼完整性,拿來可以直接運作展示)
<style scoped>
.water-analysis {
height: 100%;
overflow: auto;
}
.content-box {
height: 100%;
}
.tab-pane-box {
height: calc(100% - 62px);
}
</style>
三、總結
寫部落格是為了記筆記!