1、写一个提示框组件:

message.vue

<template>
  	<div>
      <!-- 全局提示框 -->
      <div  v-show="visible && type==1" class="dialog-tips dialog-center">
          <div><img src="../../static/image/message.png"/>{{message}}</div>
      </div>
      
      <div  v-show="visible && type==2" class="dialog-tips dialog-center">
          <div><img src="../../static/image/message2.png"/>{{message}}</div>
      </div>
  	</div>
</template>
<script>
export default {
  data() {
    return {
      visible: false,
      message: "",
      type:1,
    };
  }
};
</script>
<style lang="less">
.dialog-tips{
    position:absolute;
    z-index: 100;
    max-width: 90vw;
    height:6vw;
    white-space: nowrap;
    background-color: #fff;
    border-radius:3vw;
    padding-left:10vw;
    padding-right:3vw;
    left:50%;
    top:8vw;
	transform: translate(-50%);
	animation: name 2s ease-in;
    div{
    	font-size:2.6vw;
    	line-height:6vw;
    	width:100%;
    	overflow:hidden;
    	color:rgba(182, 142, 100, 1);
    	img{
    		display:block;
    		position:absolute;
    		bottom:0;
    		left:0;
    		width:8vw;
    	}
    }
}
@-webkit-keyframes name{
	0%{left:100%;}
	20%{left:50%;}
	80%{left:50%;}
	100%{left:-100%;}
}

</style>

2、写一个调用此组建的js

toast.js

import ToastComponent from '../components/message.vue'
const Toast = {};

// 注册Toast
Toast.install = function (Vue) {
    // 生成一个Vue的子类
    // 同时这个子类也就是组件
    const ToastConstructor = Vue.extend(ToastComponent);
    // 生成一个该子类的实例
    const instance = new ToastConstructor();
    // 将这个实例挂载在我创建的div上
    instance.$mount(document.createElement('div'));
    // 并将此div加入全局挂载点内部
    document.body.appendChild(instance.$el);
    //定义一个外部的变量,用于控制调用多次提示组件时,清除延时器
    let timer;
    // 通过Vue的原型注册一个方法
    // 让所有实例共享这个方法 
    const message_main={
    	all_message(msg,type,duration){
    		clearTimeout(timer);
    		timer=setTimeout(() => {
	            instance.visible = false;
	        }, duration);
    		instance.message = msg;
	        instance.visible = true;
	        instance.type=type;
	        
    	},
    	success(msg,duration = 2000){
	        this.all_message(msg,1,duration);
    	},
    	error(msg,duration = 2000){
	        this.all_message(msg,2,duration);
    	},
    }
    //将方法挂载全局
    Vue.prototype.$myToast = message_main;
}

export default Toast

3、在main.js中全局使用

//自定义提示框
import Toast from './utils/toast';
Vue.use(Toast);//启用新的提示组件

4、在需要使用的界面调用就可以了

methods:{
    toast1(){
		this.$myToast.success('这是提示信息');
    },
    toast2(){
		this.$myToast.error('这是提示信息');
    }
},

结果预览:

Logo

前往低代码交流专区

更多推荐