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>

效果如下


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM