(一) 创建组件
在src/components/Toash.vue文件中,创建一个组件
<template>
<div class="toast" v-show="isShow">
<h2 style="color: red;">{{message}}</h2>
</div>
</template>
<script>
export default {
name: "Toast",
data() {
return {
message: "提示文字,提示文字",
isShow: false,
};
},
methods: {
show(message, duration) {
this.isShow = true;
this.message = message;
setTimeout(() => {
this.isShow = false;
}, duration);
},
},
};
</script>
(二) 将组件封装为插件
将组件封装在自己创建的 src/myPlugin.js 文件中
import Toast from "./components/Toash";
const obj = {};
//参数Vue是install自带的,而且就是Vue
obj.install = function (Vue) {
//1. 创建组件构造器
const toastConstruct = Vue.extend(Toast);
// 2. new的方式,根据组件构造器,可以创建一个组件对象
const toast = new toastConstruct();
// 3.将组件对象,手动挂着到某一个元素上
toast.$mount(document.createElement('div'));
// 4.toast.$el对应的就是div
document.body.appendChild(toast.$el)
Vue.prototype.$toast = toast;
}
export default obj;
(三) 应用插件
在src/main.js注册插件
import MyPlugin from "./myPlugin.js";
//.....
Vue.use(MyPlugin);
//....
(四) 使用插件
在另一个组件中调用插件的show方法, 其中显示的“调用”文字将在1.5s后被隐藏
export default {
//...
mounted() {
this.$toast.show('调用', 1500);
},
};