Vue中自定义Toast插件
Toast组件用于展示提示信息,属于项目全局都可以使用。
1. Toast.vue
<template>
<div class="toast" v-show="isShow">
{{ message }}
</div>
</template>
<script>
export default {
name: "Toast",
data() {
return {
message: "",
isShow: false,
};
},
methods: {
show(msg, delay = 2000) {
this.message = msg;
this.isShow = true;
setTimeout(() => {
this.message = "";
this.isShow = false;
}, delay);
},
},
};
</script>
<style scoped>
.toast {
position: fixed;
top: 50%;
left: 50%;
transform: translate(-50%, -50%);
padding: 10px 12px;
z-index: 10;
color: #fff;
background: rgba(0, 0, 0, 0.7);
}
</style>
2. 注册插件
/**
* 自定义插件 Toast 消息提示框
* index.js,与Toast组件在同一文件夹下
*/
import Toast from "./Toast.vue"
const obj = {};
obj.install = function (Vue) {
// 1. 创建组件构建器
const toastConstructor = Vue.extend(Toast);
// 2. new ,创建组件对象
const toast = new toastConstructor();
// 3. 手动挂载到某一个元素上
toast.$mount(document.createElement("div"));
// 4. toast.$el 就有相应元素
document.body.appendChild(toast.$el);
// 挂载到 vue
Vue.prototype.$toast = toast;
}
export default obj;
3. main.js 中使用
// 导入自定义插件 Toast
import toast from "@/components/common/toast/index.js"
// 使用自定义插件 toast
Vue.use(toast);
4. 组件中使用
this.$toast.show("xxxxxx"); // 消息弹框显示xxxxx,默认2s后消失
this.$toast.show("xxxxxx!", 3000);// 消息弹框显示xxxxx,3s后消失
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步