Vue全局弹窗组件

想要实现函数式调用,不能用Vue.component()注册

需要写一个js文件,一个 vue文件

-------------------------分割线-----------------------------------------------

首先是js文件:

import ToastComponent from './index.vue'

import router from '@/router'

const Toast = {};

// 注册Toast

Toast.install = function(Vue) {

const ToastConstructor = Vue.extend(ToastComponent)

//new出来的元素,是不在根元素下的,需要手动添加路由,否则如果需要路由跳转,是没办法实现的,这里很重要

const instance = new ToastConstructor({ router });

instance.$mount()

document.body.appendChild(instance.$el)

/**

* msg:提示小时

* flag:true 展示,false隐藏

id:需要传递参数的话,在这里定义

* */

Vue.prototype.$toast = (msg, flag, id, duration = 1500) => {

instance.message = msg;

instance.visible = flag;

instance.id = id

// setTimeout(() => {

// instance.visible = false;

// }, duration);

}

}

export default Toast

-------------------------分割线-----------------------------------------------

然后是.vue文件

<template>

<!-- 全局提示框 -->

<div v-show="visible" class="global_tip">

<div class="title">

<el-badge is-dot class="item" type="warning">

<span>信息提醒</span>

</el-badge>

<span class="close" @click="visible = false"></span>

</div>

<div class="content" @click="checkMessage">{{ message }}</div>

</div>

</template>

<script>

export default {

name: "dialogTip",

data() {

return {

visible: false,

message: "",

id: ""

};

},

methods: {

checkMessage() {

this.$router.push({

path: "/userCenter/message",

query: { id: this.id }

});

}

}

};

</script>

<style lang="scss">

.global_tip {

width: 300px;

position: fixed;

.title {

height: 40px;

line-height: 40px;

background: url("../../assets/icon/dialog_line.png") no-repeat;

background-size: 100% 100%;

color: #fff;

display: flex;

justify-content: space-between;

padding: 0 14px;

.close {

width: 12px;

height: 12px;

background: url("../../assets/icon/close.png") no-repeat;

background-size: 100% 100%;

margin: 14px 0 0 0;

cursor: pointer;

}

.el-badge__content.is-fixed.is-dot {

top: 12px;

right: -2px;

}

}

bottom: 80px;

right: 10px;

.content {

cursor: pointer;

height: 120px;

background: rgba(52, 106, 255, 0.4);

color: #fff;

padding: 20px;

}

}

</style>

-------------------------分割线-----------------------------------------------

在main.js内注册

// 全局提示

import Toast from './components/dialogTip/dialogTip'

Vue.use(Toast)

-------------------------分割线-----------------------------------------------

使用:

this.$toast(res.data[0]["title"],true,res.data[0]['messageId']);

-------------------------分割线-----------------------------------------------

如果需要关闭

this.$toast('',false);

Logo

魔乐社区(Modelers.cn) 是一个中立、公益的人工智能社区,提供人工智能工具、模型、数据的托管、展示与应用协同服务,为人工智能开发及爱好者搭建开放的学习交流平台。社区通过理事会方式运作,由全产业链共同建设、共同运营、共同享有,推动国产AI生态繁荣发展。

更多推荐