不知道大家在用一些UI框架,比如Element-ui的時候,有沒有覺得一些全局組件。this.$message(),this.Toast()等,用起來很爽。他們不像其他的組件,需要去導入,去注冊。麻煩的很。
看了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) // 創建的是一個組件構造器,不是實例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元素渲染完成后執行回調   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使用組件
1.全局注冊
import Vue from 'vue';import Message from '@/components/common/message';Vue.use(Message);
2.調用方法
 private test1() {  this.$message("這是一條普通消息"); } private test2() {  this.$message.success("這是一條成功消息");  // this.$message("這是一條成功消息", "success"); } private test3() {  this.$message.error("這是一條失敗消息");  // this.$message("這是一條失敗消息", "error"); }以上就是本文的全部內容,希望對大家的學習有所幫助,也希望大家多多支持武林網。
新聞熱點
疑難解答