寫在前面
install 在實際開發中如果你只是一個簡單的業務實現者,那么大部分時間你是用不到install的,因為你用到的基本上都是別人封裝好的插件、組件、方法、指令等等,但是如果你需要給公司的架構做建設,install就是你避不開的一個知識,本次我們認識一下install的作用和他的一些使用方法,下面的三個例子均可以不用install進行實現,使用instal僅僅是為了演示用,望知悉。
install 介紹
install 本身不是一個方法,他是vue掛載時約定的一個方法,可以簡單的理解為當app.use的時候,那么install的方法就會被調用,這么簡單直接的理解也是沒錯的。
install 創建一個插件
- 創建一個plugin目錄
- 創建一個addOne的目錄
- 創建一個index.js的文件
// 簡單寫一個加一的操作插件 沒有意義 純演示使用
const addOne = (num) => {if (typeof num !== 'number') {console.warn('請給整數謝謝🙏');return NaN;}return num + 1;
}export const addOnePlugin = {install: (app) => {app.config.globalProperties.$addOne = addOne;}
}
install 創建一個組件
- 創建一個components文件夾
- 創建一個GlobleComponent文件夾
- 創建一個index.vue的文件
<template><h4>GlobleComponent</h4>
</template><script setup>
</script><style>
</style>
- 創建一個index.js
// 僅僅引入一個vue文件,沒有意義,演示使用
import GlobleComponent from './index.vue'
export const GlobleComponentInstall = {install: (app) => {app.component('GlobleComponent', GlobleComponent)}
}
install創建一個指令
- 創建一個directives文件夾
- 創建一個CorlorCustom文件夾
- 創建一個index.js的文件
// 僅僅是將顏色按照傳入的進行更改,沒有意義,演示用
export const colorCustom = {install: (app) => {app.directive('color-custom', {mounted(el, binding) {binding.value && (el.style.color = binding.value);}})}
}
統一在main.js 中引入使用
import { createApp } from 'vue'
import App from './App.vue'
import { router } from './routers/index.js'
// 引入 自定義指令
import {colorCustom } from './directives/CorlorCustom/index.js'
// 引入 自定義插件
import {addOnePlugin} from './plugins/addOne/index.js'
// 引入自定義組件
import {GlobleComponentInstall} from './components/GlobleComponent/index.js'const app = createApp(App);
app.use(router);
app.use(colorCustom);
app.use(addOnePlugin);
app.use(GlobleComponentInstall);
app.mount('#app')
頁面上使用
<template><!-- 使用自定義指令 --><h4 v-color-custom="'#ccc'">HELLO_C</h4><!-- 使用自定義插件 --><h4>{{ optionNum }}</h4><!-- 使用自定義組件 --><GlobleComponent />
</template><script setup>
import { onMounted,ref,getCurrentInstance } from "vue";
const { proxy } = getCurrentInstance()const num = ref(9);
const optionNum =proxy.$addOne(num.value);</script><style scoped>
h4 {color: #f40;
}
</style>