效果圖:
放代碼:
組件文件路徑:components/message/index.vue
<template>
<!-- 全局提示框 -->
<div class="fixed-message" v-show="visible">
<div v-show="visible && type === 'success'" class="success">{{txt}}</div>
<div v-show="visible && type === 'fail'" class="fail">{{txt}}</div>
<div v-show="visible && type === 'warning'" class="warning">{{txt}}</div>
</div>
</template>
<script>
export default {
data() {
return {
visible: false,
txt: "",
type: "",
}
}
}
</script>
<style lang="scss" scoped>
.fixed-message {
position: fixed;
top: 0;
left: 0;
z-index: 99999;
width: 100%;
height: 1.2rem;
>div {
width: 100%;
height: 100%;
color: #FFF;
text-align: center;
line-height: 1.2rem;
position: relative;
top: 0rem;
animation: message 0.5s ease-in-out;
}
}
@keyframes message {
0% {
top: -1.2rem;
}
100% {
top: 0rem;
}
}
.success {
background: #07c160;
}
.fail {
background: #ee0a24;
}
.warning {
background: #ff976a;
}
</style>
組件文件路徑:components/message/message.js
import MessageComponent from './index.vue';
const Message = {};
Message.install = function (Vue) {
const MessageConstructor = Vue.extend(MessageComponent);
const instance = new MessageConstructor();
instance.$mount(document.createElement('div'));
document.body.appendChild(instance.$el);
let timer;
const MsgMain = {
show_message(txt, type) {
clearInterval(timer);
timer = setTimeout(() => {
instance.visible = false;
}, 1500);
instance.txt = txt;
instance.type = type;
instance.visible = true;
},
success(txt, type = 'success') {
this.show_message(txt, type);
},
fail(txt, type = 'fail') {
this.show_message(txt, type);
},
warning(txt, type = 'warning') {
this.show_message(txt, type);
}
}
Vue.prototype.$message = MsgMain;
};
export default Message;
main文件路徑:main.js
import message from './components/Message/message';
Vue.use(message); // 全局提示框
調(diào)用組件文件路徑:index.vue
<template>
<div class="mages">
<button class="btn success" @click="handSuccess()">success</button>
<button class="btn fail" @click="handFail()">fail</button>
<button class="btn warning" @click="handWarning()">warning</button>
</div>
</template>
<script>
export default {
methods: {
handSuccess() {
this.$message.success('I am success ~~~');
},
handFail() {
this.$message.fail('I am fail ~~~');
},
handWarning() {
this.$message.warning('I am warning ~~~');
},
}
}
</script>
<style lang="scss" scoped>
.mages {
overflow-y: scroll;
}
.btn {
width: 90%;
margin-left: 5%;
margin-top: 0.5rem;
height: 1.2rem;
font-size: 0.4rem;
color: #FFF;
border-radius: 1rem;
background: rgb(126, 154, 245);
}
.btn:nth-child(1) {
margin-top: 8rem;
}
.success {
background: #07c160;
}
.fail {
background: #ee0a24;
}
.warning {
background: #ff976a;
}
</style>