在Vue2项目里实现一个全局组件Toast,并将其注册到Vue的原型链中。
实现 this.$toast.show({ message: 'Hello'}), this.$toast.hide() 方法,能动态展示弹窗内容。
1 创建Toast组件
新建components/toast/toast.vue文件,实现弹窗组件功能
<template>
<div v-show="visible" class="toast">{{ message }}</div>
</template>
<script>
export default {
data() {
return {
message: '',
visible: false
};
},
methods: {
show(val) {
this.visible = true;
this.message = val;
},
hide() {
this.visible = false;
}
}
};
</script>
<style scoped>
.toast {
position: fixed;
top: 50%;
left: 50%;
transform: translate(-50%, -50%);
padding: 10px 20px;
background-color: #000;
color: #fff;
}
</style>
2 基于Vue.extend创建组件实例
新建components/toast/index.js
import Vue from 'vue';
import ToastComponent from '@/components/Toast.vue';
// 使用 Vue.extend 创建一个可以扩展的构造函数
const ToastConstructor = Vue.extend(ToastComponent);
// 显示 Toast 组件
function show(options = {}) {
// 创建 Toast 组件的实例
const toastInstance = new ToastConstructor({
el: document.createElement('div'),
data: {
message: ''
}
});
// 将 Toast 组件实例添加到页面中
document.body.appendChild(toastInstance.$el);
// 调用 Toast 组件实例的 show 方法来显示组件
toastInstance.show(options);
}
// 隐藏 Toast 组件
function hide() {
// 创建 Toast 组件的实例
const toastInstance = new ToastConstructor();
// 调用 Toast 组件实例的 hide 方法来隐藏组件
toastInstance.hide();
}
// 导出
export default {
install(Vue) {
// 将 show 和 hide 方法注册到 Vue 原型链上,使其成为全局可用的方法
Vue.prototype.$evaluate = {
show,
hide
};
}
};
3 在main.js中引入
import Toast from '@/components/toast'
Vue.use(Toast)
然后就可以在任意位置调用this.$toast.show({ message: 'Hello'})