不知道大家在用一些UI框架虐秋,比如Element-ui的時候榕茧,有沒有覺得一些全局組件。this.$message(),this.Toast()等客给,用起來很爽用押。他們不像其他的組件,需要去導(dǎo)入靶剑,去注冊蜻拨。麻煩的很。
看了Element的源碼桩引,自己也擼了一個缎讼。其中包括了以前沒有接觸過的插件知識,哎坑匠,感覺自己對Vue的理解還是不夠休涤,只停留在了使用的這階段。需要更多的往深層次的地方去鉆笛辟。不說廢話了功氨,直接上代碼。
效果演示
全局組件需要一個index.js文件去注冊
BlogMessage.vue
這里的script是用ts寫的手幢。大家只需將這里稍做修改就可以了
<template>
<transition name="slide">
<div class="message-wrap" :class="type" v-if="visible">
<div class="content">{{content}}</div>
</div>
</transition>
</template>
<script lang='ts'>
import { Component, Vue, Watch, Prop } from "vue-property-decorator";
@Component({
components: {}
})
export default class extends Vue {
private content: string = "";
private visible: boolean = false;
private type: string = "info"; // 'success','error'
private startTimer() {
window.setTimeout(() => {
this.visible = false;
}, 3000);
}
private mounted() {
this.startTimer();
}
}
</script>
<style scoped lang="scss">
.message-wrap {
position: fixed;
background-color: #44b0f3;
color: #ffffff;
left: 40%;
width: 20%;
top: 25px;
height: 40px;
z-index: 1001;
border-radius: 4px;
text-align: center;
border: 1px solid #ebeef5;
.content {
line-height: 40px;
}
}
.error {
background-color: #fef0f0;
color: #f56c6c;
}
.success {
background-color: #f0f9eb;
color: #67c23a;
}
.slide-enter-active,
.slide-leave-active {
transition: all 0.3s cubic-bezier(1, 0.5, 0.8, 1);
transition: all 0.2s ease;
}
.slide-enter,
.slide-leave-to {
transform: translateY(-20px);
opacity: 0;
}
</style>
index.js
import Vue from 'vue'
import BlogMessage from './BlogMessage.vue'
const MessageBox = Vue.extend(BlogMessage) // 創(chuàng)建的是一個組件構(gòu)造器捷凄,不是實例
const Message = {
install: (options, type, duration) => {
if (options === undefined || options === null) {
options = {
content: ''
}
} else if (typeof options === 'string' || typeof options === 'number') {
options = {
content: options
}
if (type != undefined && options != null) {
options.type = type;
}
}
let instance = new MessageBox({
data: options
}).$mount()
document.body.appendChild(instance.$el) // 添加dom元素
Vue.nextTick(() => { // dom元素渲染完成后執(zhí)行回調(diào)
instance.visible = true
})
}
}
Vue.prototype.$message = Message.install;
['success', 'error'].forEach(type => {
Vue.prototype.$message[type] = (content) => {
return Vue.prototype.$message(content, type)
}
})
export default Message
使用組件
- 全局注冊
import Vue from 'vue';
import Message from '@/components/common/message';
Vue.use(Message);
- 調(diào)用方法
private test1() {
this.$message("這是一條普通消息");
}
private test2() {
this.$message.success("這是一條成功消息");
// this.$message("這是一條成功消息", "success");
}
private test3() {
this.$message.error("這是一條失敗消息");
// this.$message("這是一條失敗消息", "error");
}