定義vue插件
很多同學看不懂export default關鍵詞,特意寫明導出方式
具體es6語法export default
- 方法1(工作中常用)
// getModules.js
import Vue from 'vue'
export default{
install(Vue, options) {
// 1.添加實例方法
Vue.prototype.setImgSize = function (param) { ... }
// 2.添加全局方法或者屬性
Vue.Method = function() { ... }
// 3.注冊全局組件
Vue.component('modules', {...})
// ...
}
}
- 方法2 官方文檔
// getModules.js
// 參數1是Vue構造器禽笑,參數2是可選對象
MyPlugin.install = function (Vue, options) {
// 1.添加實例方法
// 2.添加全局方法或者屬性
// ...
}
export default MyPlugin
調用vue插件
import Vue from 'vue'
import modules from './getModules.js'
Vue.use(modules)
注意點:
1坯墨、通過Vue.use(MyPlugin)使用封恰,本質上是調用MyPlugin.install(Vue)
2温赔、使用插件必須在new Vue()啟動應用之前完成拄衰,實例化之前就要配置好它褪。
3、如果使用Vue.use多次注冊相同插件翘悉,那只會注冊成功一次茫打。
案例:如何展示首頁?首頁由多個模塊組合,比如輪播圖老赤、熱門推薦轮洋、秒殺模塊等等,后臺允許配置重復模塊抬旺,首頁展示須按照后臺返回模塊順序展示弊予,這時候推薦結合render函數動態(tài)渲染首頁,與以往的分類开财、搜索列表頁不一致汉柒,它們是靜態(tài)的。
- 第一步:根據首頁展示拆分模塊责鳍,各個模塊對應一個vue文件碾褂,各自vue文件中處理各自的邏輯;比如:moduleBanner.vue历葛、moduleMayLike.vue正塌、moduleNoticeBoard.vue對應有輪播圖、猜你喜歡恤溶、廣告通知模塊等等
- 第二步:調用接口獲取數據乓诽、同步到狀態(tài)管理器
// 設置 首頁組件
import moduleBanner from '@/views/index/moduleBanner.vue'
import moduleMayLike from '@/views/index/moduleMayLike.vue'
import moduleNoticeBoard from '@/views/index/moduleNoticeBoard.vue'
// 首頁用到的組件同步到vuex
this.$store.commit("commonComponents", [moduleBanner, moduleMayLike, moduleNoticeBoard]);
// 發(fā)送請求
indexApi.cmsFloor(this.$route.query.json_id)
.then((res) => {
if(res.result.code == 200) {
// 接口返回數據同步到vuex
this.$store.commit("floorData", res.rows)
}
})
.catch((error) => {
console.log(error);
})
- 第三步:狀態(tài)管理器getters方法中定義componentsSort函數,獲取首頁模塊組件數組
const getters = {
componentsSort(state){
let data = state.indexData;
let componentsArray = state.commonComponents;
let componentList=[]
// 遍歷循環(huán)接口返回數據咒程,封裝return組件數組
for(var i=0;i<data.length;i++){
for(var j=0;j<componentsArray.length;j++){
if(data[i].moduleName == componentsArray[j].name){
componentList.push(componentsArray[j]);
break;
}
}
}
return componentList
}
}
第四步:定義插件鸠天,用于注冊全局組件modules,這個組件包含首頁所有的模塊
export default {
install(Vue) {
// 注冊全局組件modules
Vue.component('modules', {
render: function(createElement, context) {
if(!this.componentList) return
return createElement("div",
// 遍歷數組孵坚,動態(tài)生成組件
this.componentList.map(function(item, index) {
return createElement(item, {
attrs: {level: index}
})
})
)
},
computed: {
// 獲取組件數組
componentList() {
return this.$store.getters.componentsSort
}
}
})
}
}
第五步:調用插件粮宛、使用全局組件modules
// 調用插件
import modules from './util/getModules.js'
Vue.use(modules)
// 使用全局組件modules
<template>
<div class="index">
<SearchHeader></SearchHeader>
<modules></modules>
<GoTop></GoTop>
</div>
</template>