Vue如何封装Toast组件

这应该是上升到插件了

首先创建一个Toast.vue文件
<template>
    <transition name="demo">
        <div class="toast" v-show="theToast">
            {{msg}}
        </div>
    </transition>
</template>
 
<script>
    export default {
        data() {
            return {
                theToast: false,
                msg: ""
            };
        }
    };
</script>
 
<style lang="scss" scoped>
    .toast {
        position: fixed;
        top: 40%;
        left: 50%;
        margin-left: -15vw;
        padding: 2vw;
        width: 30vw;
        font-size: 4vw;
        color: #fff;
        text-align: center;
        background-color: rgba(0, 0, 0, 0.8);
        border-radius: 5vw;
        z-index: 999;
    }
     
    //.demo-enter-active,
    .demo-leave-active {
        transition: 0.3s ease-out;
    }
     
    .demo-enter {
        opacity: 0;
        transform: scale(1.2);
    }
     
    .demo-leave-to {
        opacity: 0;
        transform: scale(0.8);
    }
</style>

然后在创建一个index.js文件

import ToastComponent from './Toast.vue'// 引入先前写好的vue

const Toast = {};

// 注册Toast
Toast.install = function (Vue) {
    // 生成一个Vue的子类
    const ToastConstructor = Vue.extend(ToastComponent)
    // 生成一个该子类的实例
    const instance = new ToastConstructor();

    // 将这个实例挂载在我创建的div上
    // 并将此div加入全局挂载点内部
    instance.$mount(document.createElement('div'))
    document.body.appendChild(instance.$el)

    // 通过Vue的原型注册一个方法
    // 让所有实例共享这个方法 <br>    // 其中的duration是持续时间
    Vue.prototype.$toast = (msg, duration = 1250) => {
        instance.msg = msg;
        instance.theToast = true;

        setTimeout(() => {

            instance.theToast = false;
        }, duration);
    }
}
// 导出
export default Toast

最后在main.js中引入.vue文件 Vue.use()下

import Toast  from '@/components/Toast' // message 提示消息插件
Vue.use(Toast)

然后在所有的组件中通过 this.$toast('提示信息'); 都可以使用
应用场景还是挺多的,毕竟提示信息吗。
比如请求数据的时候,提示,数据请求成功
加入购物车时 提示 加入购物车成功 …

这里呢设计到一个知识点vue.extend 这里发一个连接可查看 https://cn.vuejs.org/v2/api/#Vue-extend

  • 3
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值