创建一个message.vue组件
<template>
<transition name="message-transition">
<div v-show="show" class="message">
<div class="message-content">{{ content }}</div>
</div>
</transition>
</template>
<script>
export default {
name: "Message",
computed: {
show() {
return this.$store.state.message.show;
},
content() {
return this.$store.state.message.content;
}
}
}
</script>
<style scoped>
.message {
display: flex;
flex-direction: column;
justify-content: center;
align-items: center;
position: fixed;
top: 0;
right: 0;
bottom: 0;
left: 0;
z-index: 10;
pointer-events: none;
}
.message-content {
max- 320px;
padding: 10px 30px;
border-radius: 10px;
background-color: rgba(0, 0, 0, 0.8);
font-size: 30px;
color: #fff;
line-height: 60px;
}
.message-transition-enter-active, .message-transition-leave-active {
transition: opacity .5s;
}
.message-transition-leave, .message-transition-enter-to {
opacity: 1;
}
.message-transition-enter, .message-transition-leave-to {
opacity: 0;
}
</style>
相同目录下再建一个index.js文件
import Vue from 'vue' import Message from './index.vue' export default { install() { Vue.component(Message.name,Message); Object.defineProperty(Vue.prototype,'$message', { value(content) { this.$store.dispatch('message/start',content); } }); } }
在store文件夹中建一个message.js文件
const message = {
namespaced: true,
state: {
show: false,
content: '',
duration: '2000',
timeoutId: 0,
},
mutations: {
setShow(state,flag) {
state.show = flag;
},
setContent(state,content) {
state.content = content;
},
setDuration(state,duration) {
state.duration = duration;
},
setTimeoutId(state, timeoutId) {
state.timeoutId = timeoutId;
}
},
actions: {
start(context, content) {
clearTimeout(context.state.timeoutId);
context.commit('setShow', true);
context.commit('setContent', content);
const timeoutId = setTimeout(() => {
context.commit('setShow', false);
},context.state.duration);
context.commit('setTimeoutId', timeoutId);
}
}
}
export default message
然后再store文件中的index.js引入使用
import Vue from 'vue'
import Vuex from 'vuex'
import message from '@/store/message.js'
Vue.use(Vuex)
export default new Vuex.Store({
state: {
},
mutations: {
},
actions: {
},
modules: {
message
}
})
之后在main.js引入index.js并全局使用就可以了
调用
<template>
<div></div>
</template>
<script>
export default {
name: "index",
created() {
setTimeout(() => {
this.$message('你好');
},1000);
}
}
</script>
<style scoped>
</style>