zoukankan      html  css  js  c++  java
  • 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>

    效果如下

  • 相关阅读:
    PHP MVC运用
    17个方法防止dedeCMS织梦网站被黑挂木马
    少有人走的路
    你有选择的自由
    产品经理需要掌握哪些能力
    产品经理的工作流程
    Weave实现跨主机容器互联
    转载【docker】CMD ENTRYPOINT 的使用方法
    Docker:发布镜像问题denied: requested access to the resource is denied的解决方法
    Docker Dockerfile基本配置
  • 原文地址:https://www.cnblogs.com/z-j-c/p/12994076.html
Copyright © 2011-2022 走看看