我們在利用vue的cli來做開發(fā)的時候,我們會引入一些框架以及各種插件,我們經常能看到類似于
Vue.use(Element, {
size: Cookies.get('size') || 'medium'
})
Vue.use(Vant)
這樣的代碼,老弟,牛X哈,這代碼一看就高大上呀。
實際上,這個是通過vue官方暴露出來的開發(fā)插件的install方法來實現(xiàn)的,下面我弟弟就教你如何來實現(xiàn)這種“牛X”操作.
我們先來看官網給出的install解釋

QQ截圖20201028104308.png
看起來也不過如此嘛,讓我們手動操作一下!
我們先來進行工具類的封裝
首先呢,我們在我們的utils(你隨意開心命名)文件夾下定義一個叫tools.js的js文件
然后呢。
//tools.js
const exampleFunc {
install (Vue, options) {
Vue.prototype.customerTools = {
//這里隨便粘貼了兩個方法作為示例
//深度拷貝
deepClone(source) {
if (!source && typeof source !== 'object') {
throw new Error('error arguments', 'shallowClone');
}
const targetObj = source.constructor === Array ? [] : {};
for (const keys in source) {
if (source.hasOwnProperty(keys)) {
if (source[keys] && typeof source[keys] === 'object') {
targetObj[keys] = source[keys].constructor === Array ? [] : {};
targetObj[keys] = deepClone(source[keys]);
} else {
targetObj[keys] = source[keys];
}
}
}
return targetObj;
},
//獲取網頁url?后面的參數(shù)值
getQueryString(name) {
var reg = new RegExp('(^|&)' + name + '=([^&]*)(&|$)', 'i');
var r = window.location.search.substr(1).match(reg);
if (r != null) {
return unescape(r[2]);
}
return null;
}
}
}
export default exampleFunc
至此,我們的工作進行了99%,剩下那1%,我們在src/main.js文件里面進行,這個是我們程序的入口文件,主要是用來加載各種公共組件和方法的
//main.js
import exampleFunc from './utils/tools'
Vue.use(exampleFunc)
//好了,沒啦。是不是看起來很簡單?
接下來我們就在各種頁面里調用方法就可以啦
//example.vue
mounted() {
let array = [...]
//嘗試調用一下深拷貝方法,ok!
this.customerTools.deepClone(array)
},
工具類函數(shù)被我們成功送上天了。下面就剩組件了,到這里,怎么利用install創(chuàng)建全局組件我們是不是心里都有點筆數(shù)了,一奶同胞呀。
我們創(chuàng)建一個a.vue在main.js同級的文件夾views下
//a.vue
<template>
<div>
組件
</div>
</template>
<script>
export default {
}
</script>
<style scoped>
</style
然后呢,我們在統(tǒng)計文件夾下創(chuàng)建一個js文件,就叫a-export.js
//a-export.js
import acomponent from './Cmponent.vue'
const avue = {
install (Vue,options) {
Vue.component('a-vue',acomponent)//前面的a-vue就是我們后面使用的組件名稱,后面的acomponent是我們導入的組件文件
}
}
export default avue
然后呢,跟我們創(chuàng)建工具類方法引用一樣
//main.js
import avue from './views/a-export.js'
Vue.use(avue)
然后你頁面就可以使用這個avue組件啦
//某某某.vue
<template>
<div>
<a-vue><a-vue>
</div>
</template>
裝逼完畢,呂某人吃飯去了~~~~感覺對您有用的麻煩給個小心心,謝謝!