Vue3 插件開發詳解嚐鮮版
前言
vue3.0-beta 版本已經發布了一段時間了,正式版本據說在年中發佈(直播的時候說的是年中還是年終,網上傳聞說是6月份)。嘴上說着學不動,身體卻很誠實地創建一個vue3的項目,興致勃勃地引入 vue2 插件的時候,眉頭一皺,發現事情並沒有那麼簡單。
瀏覽器無情地拋出了一個錯誤:
Uncaught TypeError: Cannot set property '$toast' of undefined
不是說兼容vue2的寫法嗎,插件不兼容,這是鬧哪樣?發下牢騷之後還是得解決問題。研究插件的代碼,是這麼實現的
var Toast = {};
Toast.install = function (Vue, options) {
Vue.prototype.$toast = 'Hello World';
}
module.exports = Toast;
複製代碼
vue2 插件的時候會暴露一個 install 方法,並通過全局方法 Vue.use() 使用插件。install 方法的第一個參數是 Vue 構造器,插件的方法就添加在 Vue 構造器的原型對象上。通過 new Vue() 實例化後,在組件中就能調用 this.$toast 使用組件了。(具體實現可以參考我之前的一篇文章:Vue.js 插件開發詳解,下面也是基於這個插件demo對比修改)。
而 vue3 的 install 方法不是傳入 Vue 構造器,沒有原型對象,Vue.prototype 是 undefined,所以報錯了。vue3 採用依賴注入的方式,在插件內部利用 provide 和 inject 並暴露出一個組合函數,在組件中使用。
插件實現
基本框架
下面先實現一個插件的基本框架。
import { provide, inject } from 'vue';
const ToastSymbol = Symbol(); // 用Symbol創建一個唯一標識,多個插件之間不會衝突
const _toast = () => {} // 插件的主體方法
export function provideToast(config) { // 對外暴露的方法,將 _toast 方法提供給後代組件
provide(ToastSymbol, _toast);
}
export function useToast() { // 後代組件可以從該方法中拿到 toast 方法
const toast = inject(ToastSymbol);
if (!toast) {
throw new Error('error');
}
return toast;
}
複製代碼
組件使用
在 provideToast 方法中,提供了 _toast 方法,那在根組件中 調用 provideToast 方法,傳入插件參數,子組件中就能使用 toast 功能了。
// app.vue 根組件
import { provideToast } from 'vue2-toast';
export default {
setup() {
provideToast({
width: '200px', // 配置toast寬度
duration: 2000 // 配置toast持續顯示時長
});
}
};
複製代碼
在 useToast 方法中,返回了 toast 方法,那在所有的後代組件中調用 useToast 方法,就能拿到 toast 方法了。
// child.vue 子組件
import { useToast } from 'vue2-toast';
export default {
setup() {
const Toast = useToast(); // 所有的子組件都要從useToast拿到toast方法
Toast('Hello World');
}
};
複製代碼
數據響應
想要控制 toast DOM 元素的顯示隱藏,以及提示文本的變化,需要創建響應式的數據,在 vue3 中可以通過 reactive 方法創建一個響應式對象。
const state = reactive({
show: true, // DOM元素是否顯示
text: '' // 提示文本
});
複製代碼
掛載DOM
在頁面中顯示一個 toast,那就免不了要創建一個 DOM 並掛載到頁面中。在 vue2 中是通過Vue.extend 創建一個子類,將子類生成的實例掛載到某個元素中,而 vue3 中通過 createApp 方法來實現的。
const _toast = text => {
state.show = true;
state.text = text;
toastVM = createApp({
setup() {
return () =>
h('div', {
style: { display: state.show ? 'block' : 'none' } // display 設置顯示隱藏
},
state.text
);
}
});
toastWrapper = document.createElement('div');
toastWrapper.id = 'toast';
document.body.appendChild(toastWrapper); // 給頁面添加一個節點用來掛載toast元素
toastVM.mount('#toast');
};
複製代碼
完整示例
上面的每一步是這個插件的關鍵內容,接下來就是完善下細節,比如用戶配置插件的全局參數,設置 toast 的樣式,持續時間,顯示位置等,這裏就不一一細講了,完整示例如下:
import { provide, inject, reactive, createApp, h } from 'vue';
const ToastSymbol = Symbol();
const globalConfig = {
type: 'bottom', // toast位置
duration: 2500, // 持續時長
wordWrap: false, // 是否自動換行
width: 'auto' // 寬度
};
const state = reactive({
show: false, // toast元素是否顯示
text: ''
});
let [toastTimer, toastVM, toastWrapper] = [null, null, null];
const _toast = text => {
state.show = true;
state.text = text;
if (!toastVM) {
// 如果toast實例存在則不重新創建
toastVM = createApp({
setup() {
return () =>
h(
'div',
{
// 這裏是根據配置顯示一樣不同的樣式
class: [
'lx-toast',
`lx-toast-${globalConfig.type}`,
globalConfig.wordWrap ? 'lx-word-wrap' : ''
],
style: {
display: state.show ? 'block' : 'none',
width: globalConfig.width
}
},
state.text
);
}
});
}
if (!toastWrapper) {
// 如果該節點以經存在則不重新創建
toastWrapper = document.createElement('div');
toastWrapper.id = 'lx-toast';
document.body.appendChild(toastWrapper);
toastVM.mount('#lx-toast');
}
if (toastTimer) clearTimeout(toastTimer);
// 定時器,持續時長之後隱藏
toastTimer = setTimeout(() => {
state.show = false;
clearTimeout(toastTimer);
}, globalConfig.duration);
};
export function provideToast(config = {}) {
for (const key in config) {
globalConfig[key] = config[key];
}
provide(ToastSymbol, _toast);
}
export function useToast() {
const toast = inject(ToastSymbol);
if (!toast) {
throw new Error('error');
}
return toast;
}
複製代碼
總結
與 vue2 的插件比較大不同點在於,需要用到 toast 的每個組件中,都需要引入 useToast 方法,看起來會有點麻煩。不過其實這也是 vue 組合式 API 的目的,讓代碼更可讀、更容易被理解,清楚的知道這個方法就是來自這裏。正如標題所示,這是嚐鮮版,vue3 正式版還未發佈,未來會不會有更多的插件形式,咋也不敢問,至少這種還是比較穩的。