如果想看该实战系列的其他内容,请移步至 Vue.js 实战系列之实现视频类WebApp的项目开发。
项目仓库地址,欢迎 Star
实现效果
success 效果:
error 效果:
功能实现
-
自定义全局 toast 组件
在
src/common/components
目录下,创建toast
文件夹并新建toast.vue
、toast.js
文件toast.vue 创建弹窗样式
<template> <div class="toast-box"> <transition name="toast"> <div class="toast" :class="type" v-show="show"> <p>{{ message }}</p> </div> </transition> </div> </template> <script> export default { data() { return { message: '弹出框', type: 'success', show: true, }; }, }; </script> <style lang="less" scoped> .toast-box { .toast { position: fixed; left: 50%; top: 10%; transform: translate(-50%, -50%); background: rgba(255, 8, 8, 0.5); color: white; text-align: center; border-radius: 4px; font-size: 14px; line-height: 18px; padding: 0 10px; } /* 默认提示 */ .success { background: rgba(0, 0, 0, 0.5); } /* 失败提示 */ .error { background: #fe2c55; } .toast-enter-to, .toast-leave { opacity: 1; } .toast-enter-active, .toast-leave-active { transition: all ease 0.5s; } .toast-enter, .toast-enter-to { opacity: 0; } } </style>
toast.js
使用vue.extend()
构造器创建一个 “子类”// 实例化组件 import Vue from 'vue'; // 导入 toast 组件 import toast from './toast.vue'; // 创建一个toast构造器 const Toast = Vue.extend(toast); // 创建一个实例对象 let instance; // 时间,设置一个定时器 用于关闭toast提示框 let timer = null; // 设置参数 const toastMsg = (options) => { // 判断是否实例化 if (!instance) { // 创建一个实例 instance = new Toast(); // 挂载到页面 document.body.append(instance.$mount().$el); } // 设置默认时间 instance.duration = 1500; // 设置提示内容 if (typeof options === 'string') { instance.message = options; } else if (typeof options === 'object') { instance.type = options.type; instance.message = options.message; instance.duration = options.duration || 1500; } else { return; } // 展示 toast instance.show = true; timer = setTimeout(() => { instance.show = false; // 清空定时器 clearTimeout(timer); timer = null; }, instance.duration); }; export default toastMsg;
-
将创建好的构造器注册到全局上
main.js
import Vue from 'vue'; import App from './App.vue'; // ... // 自定义弹出框 import Toast from './common/components/toast/toast'; // 挂载到 Vue 上(原型链) Vue.prototype.$toast = Toast; new Vue({ router, store, render: (h) => h(App), }).$mount('#app');
-
在需要的地方使用它即可
// options === 'string' this.$toast('验证码发送成功'); // options === 'object' this.$toast({ message: '请输入正确的验证码', type: 'error', duration: 2000, });
总结
本章节需要注意的几个点:
vue.extend()
构造器的使用new Vue()/Vue.Component/Vue.extend
之间的区别- 实例化 taost 组件的实现
- 自定义全局 toast 组件
- 将 toast 添加到 Vue 原型链上方便使用
上一章节: 12. 引入Vuex实现数据管理以及登录流程的实现
下一章节: 14. 用户信息界面实现
项目整体介绍:Vue.js 项目实战之实现视频播放类WebApp的项目开发(仿抖音app)
项目仓库地址,欢迎 Star。
有任何问题欢迎评论区留言讨论。