vue3.0-beta 版本已經發布了一段時間了,正式版本聽說在年中發佈(直播的時候說的是年中仍是年終,網上傳聞說是6月份)。嘴上說着學不動,身體卻很誠實地建立一個vue3的項目,興致勃勃地引入 vue2 插件的時候,眉頭一皺,發現事情並無那麼簡單。vue
瀏覽器無情地拋出了一個錯誤:react
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對比修改)。app
而 vue3 的 install 方法不是傳入 Vue 構造器,沒有原型對象,Vue.prototype 是 undefined,因此報錯了。vue3 採用依賴注入的方式,在插件內部利用 provide 和 inject 並暴露出一個組合函數,在組件中使用。框架
下面先實現一個插件的基本框架。ide
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 方法了。post
// child.vue 子組件 import { useToast } from 'vue2-toast'; export default { setup() { const Toast = useToast(); // 全部的子組件都要從useToast拿到toast方法 Toast('Hello World'); } };
想要控制 toast DOM 元素的顯示隱藏,以及提示文本的變化,須要建立響應式的數據,在 vue3 中能夠經過 reactive 方法建立一個響應式對象。this
const state = reactive({ show: true, // DOM元素是否顯示 text: '' // 提示文本 });
在頁面中顯示一個 toast,那就免不了要建立一個 DOM 並掛載到頁面中。在 vue2 中是經過Vue.extend 建立一個子類,將子類生成的實例掛載到某個元素中,而 vue3 中經過 createApp 方法來實現的。prototype
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 正式版還未發佈,將來會不會有更多的插件形式,咋也不敢問,至少這種仍是比較穩的。