在 Vue2 時寫過一個 toast 插件。詳見 Vue | 如何封裝一個toast插件。
翻看 Vue2 的 toast 代碼可以發現核心是這句:
Vue.prototype.$toast = toast
Vue2 的時候會暴露一個 install 方法,并通過全局方法 Vue.use() 使用插件。
install 方法的第一個參數是 Vue 構造器,通過 new Vue() 實例化后,在組件中就能調用 this.$toast 使用組件了。
Vue3 的 install 方法不是傳入 Vue 構造器,沒有原型對象,Vue.prototype 是 undefined,上面的方式也就沒啥用了。
Vue3 出來有段時間了,Vue3 的變化,廣度上或者影響范圍上個人認為應該是this,在 Vue2 中到處可見 this.$router
,this.$store
等代碼。在 Vue3 中,不再推薦這種都往 prototype 中加的方式。
不妨看一看配套的 VueX 的寫法:
import { useStore } from 'vuex'
export default {
setup () {
const store = useStore()
}
}
這種方式的術語是Hook,具體可見 React 的文檔。那么我們期望的 Toast 的使用方式為:
import { useToast } from "./useToast.js";
export default{
setup() {
const Toast = useToast();
Toast("Hello World");
};
}
那么問題來了,useToast.js 這個文件應該如何編寫。
首先,明確一點我們先將 DOM 搞出來,一個居中的框,里面有提示文字。功能代碼,一定時間消失,可以使用 setTimeout() 并設置默認事件2000毫秒。
在使用 Vue 時使用的是單文件方式template,這里不妨采用 h 函數來寫,一下子高大上起來了呢。
const toastVM = createApp({
setup() {
return () =>
h(
'div',
{
class: [
'lx-toast',
],
style: {
display: state.show ? 'block' : 'none',
background: "#000",
color: "#fff",
width: '100px',
position: "fixed",
top: "50%",
left: "50%",
transform: "translate(-50%, -50%)",
padding: "8px 10px",
}
},
state.text
);
}
});
核心代碼是:display: state.show ? 'block' : 'none'
根據 state.show 的值來決定是否可以展示。
對于 state 的定義:
const state = reactive({
show: false, // toast元素是否顯示
text: ''
});
接下來是將 h 好的東西掛到 DOM 中,
const toastWrapper = document.createElement('div');
toastWrapper.id = 'lx-toast';
document.body.appendChild(toastWrapper);
toastVM.mount('#lx-toast');
最后是核心的 useToast 函數:
export function useToast() {
return function Toast(msg) {
console.log(msg)
// 拿到傳來的數據
state.show = true
state.text = msg
setTimeout(() => {
state.show = false
}, 1000);
}
}
暴露函數可以控制展示文字數據,可能還需要控制展示時間等,更多的功能可以進一步擴展。