Vue 封装全局提示组件

时间:2020-05-30
本文章向大家介绍Vue 封装全局提示组件,主要包括Vue 封装全局提示组件使用实例、应用技巧、基本知识点总结和需要注意事项,具有一定的参考价值,需要的朋友可以参考一下。

新建一个Toast组件

 1 <template>
 2   <transition name="fade">
 3     <div v-show="visible">{{message}}</div>
 4   </transition>
 5 </template>
 6 
 7 <script>
 8 export default {
 9   data () {
10     return {
11       visible: false,
12       message: ''
13     }
14   }
15 }
16 </script>
17 
18 <style scoped>
19 div {
20   padding: 5px 20px;
21   color: #fff;
22   background-color: #3596ff;
23   text-align: center;
24   position: fixed;
25   top: 30%;
26   left: 50%;
27   transform: translate(-50%, -50%);
28 }
29 /* vue动画过渡效果设置 */
30 .fade-enter-active,
31 .fade-leave-active {
32   transition: opacity .5s;
33 }
34 .fade-enter, .fade-leave-to /* .fade-leave-active below version 2.1.8 */ {
35   opacity: 0;
36 }
37 </style>

在main.js里面配置如下

import Toasts from './components/Toast'
const Toast = {
  install: function (Vue) {
    // 创建一个Vue的“子类”组件
    const ToastConstructor = Vue.extend(Toasts)
    // 创建一个该子类的实例,并挂载到一个元素上
    const instance = new ToastConstructor()
    // 将这个实例挂载到动态创建的元素上,并将元素添加到全局结构中
    instance.$mount(document.createElement('div'))
    document.body.appendChild(instance.$el)

    // 在Vue的原型链上注册方法,控制组件
    Vue.prototype.$toast = (msg, duration = 1500) => {
      instance.message = msg
      instance.visible = true
      setTimeout(() => {
        instance.visible = false
      }, duration)
    }
  }
}
Vue.use(Toast)

在组件内调用

<template>
  <div>
<button @click="onClick">1111</button>
  </div>
</template>

<script>
export default {
  name: "App",
  components: {
  },
  data() {
    return {
   
    };
  },
  methods:{
    onClick(){
    // 使用全局 toast
     this.$toast('提示内容')
    }
  }
};
</script>

<style lang="less">

</style>

效果如下

原文地址:https://www.cnblogs.com/z-j-c/p/12994076.html