Vue 動態切換元件

Vue 動態切換元件

根據API取得的資料,動態切換元件。公司需要做模板切換,使用者可以在後台選擇layout1、layout2、layout3,分別會載入不同的layout

我們將API取得的資料放在sessionStorage.siteInfo裡,
接著利用:is來做動態切換。

當是layout1時,便會切換layout-1的元件。
比較特別的是,使用:is作法不需要在components再宣告一次

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
<template>
<div>
<div :is="hotGame"></div>
</div>
</template>

import layout1 from '../12.index/hot_layout/layout-1.vue'
import layout2 from '../12.index/hot_layout/layout-2.vue';
import layout3 from '../12.index/hot_layout/layout-3.vue';

<script>
export default {
data() {
return {
hotGame: this.selectLayout()
};
},
methods: {
selectLayout() {
let layout = JSON.parse(sessionStorage.getItem('siteInfo')).site_params.hot_layout
switch (layout) {
case 'layout1':
return layout1;
case 'layout2':
return layout2;
case 'layout3':
return layout3;
}
}
}
}
</script>

動態載入

import 使用變數來動態載入模組

1
2
3
4
5
6
7
8
9
10
11
var { hot_layout } = this.$store.dispatch('index.siteInfo');
var { vendor_layout } = JSON.parse(sessionStorage.getItem('siteInfo'));
var HotGame = () => import(`@/views/12.index/hot_layout/${hot_layout}.vue`)
var VendorGame = () => import(`@/views/12.index/vendor_layout/${vendor_layout}.vue`)

var c = 'components';
export default {
components: {
Slider: () => import(`@/views/12.index/${c}/Slider.vue`),
},
}

但是這個方法取得API總會遲一步,所以暫緩沒有使用此方法,在這邊做個紀錄。

Reference


本博客所有文章除特别声明外,均采用 CC BY-SA 4.0 协议 ,转载请注明出处!