vue中的toast组件

首先在components新建组件文件夹

随后在toast.vue中写入弹框样式

<template>
	<transition name="demo">
		<div class="toast" v-show="theToast">
			{{msg}}
		</div>
	</transition>
</template>

<script>
	export default {
		data() {
			return {
				theToast: false,
				msg: ""
			};
		}
	};
</script>

<style lang="less" scoped>
	.toast {
		position: fixed;
		top: 40%;
		left: 50%;
		margin-left: -15vw;
		padding: 2vw;
		 30vw;
		font-size: 4vw;
		color: #fff;
		text-align: center;
		background-color: rgba(0, 0, 0, 0.8);
		border-radius: 5vw;
		z-index: 999;
	}
	
	.demo-enter-active,
	.demo-leave-active {
		transition: 0.3s ease-out;
	}
	
	.demo-enter {
		opacity: 0;
		transform: scale(1.2);
	}
	
	.demo-leave-to {
		opacity: 0;
		transform: scale(0.8);
	}
</style>

  随后在index.js中写下核心js部分

import ToastComponent from './toast.vue'// 引入先前写好的vue

const Toast = {};

// 注册Toast
Toast.install = function (Vue) {
    // 生成一个Vue的子类
    const ToastConstructor = Vue.extend(ToastComponent)
    // 生成一个该子类的实例
    const instance = new ToastConstructor();

    // 将这个实例挂载在我创建的div上
    // 并将此div加入全局挂载点内部
    instance.$mount(document.createElement('div'))
    document.body.appendChild(instance.$el)

    // 通过Vue的原型注册一个方法
    // 让所有实例共享这个方法 
// 其中的duration是持续时间 Vue.prototype.$toast = (msg, duration = 1250) => { instance.msg = msg; instance.theToast = true; setTimeout(() => { instance.theToast = false; }, duration); } } export default Toast

  随后在main.js之中注册

之后就可以直接使用了

使用this.$toast调用

实现效果:

原文地址:https://www.cnblogs.com/DangerousBaymax/p/9116453.html