1:首先可以創(chuàng)建一個(gè)toast文件夾,用來(lái)放toast組件和它的js文件
2、然后在main.js文件中引入toast的js文件, 并將toast插件安裝到Vue實(shí)例中,也就是掛載到實(shí)例中; Vue.use(toast)
3:一旦寫了 Vue.use() 后,它就會(huì)去 toast 的js文件里執(zhí)行 install函數(shù);
注意:use 括號(hào)中的toast 相當(dāng)于是個(gè)形參 它代表著 js 文件中的 obj 這個(gè)對(duì)象
4:接下來(lái)看一下toast.js
import Vue from "vue";
import toastcom from "./index.vue";
const toast = {};
toast.install = Vue => {
const ToastCon = Vue.extend(toastcom); //組件構(gòu)造器
const ins = new ToastCon(); //創(chuàng)建實(shí)例
ins.$mount(document.createElement("div")); //實(shí)例掛載dom
document.body.appendChild(ins.$el); //把實(shí)例化的vue添加到body中
Vue.prototype.$toast = (msg, duration = 3000) => {
//注冊(cè)為全局組件的函數(shù)
ins.message = msg;
ins.visible = true;
setTimeout(() => {
//異步執(zhí)行
ins.visible = false;
}, duration);
};
};
export default toast;
// 剩余的步驟是:
// 1.在main.js中注冊(cè)使用
// import toast from '@/dialog/index.js' //引入封裝的組件
// Vue.use(toast)
// 2.然后在任何vue文件中可以輕松的使用組件了 this.$toast('北京歡迎您')