vue 自定义插件 toast

toast/Toast.vue

<template>
  <div class="toast" v-show="isShow">
      {{text}}
  </div>
</template>

<script>
export default {
    name:'Toast',
    data(){return{
        text:'',
        isShow:false
    }},
    methods:{
        show(text, time=1500){
            this.text = text
            this.isShow = true
            setTimeout(()=>{
                this.isShow = false
            },time)
        }
    }
}
</script>

<style scoped>
.toast{
    position: fixed;
    top: 50%;
    left: 50%;
    transform: translate(-50%,-50%);
    padding:4px 10px;
    background-color: rgba(0, 0, 0, .8);
    color: #fff;
    border-radius: 5px;
    line-height: 16px;
    font-size: 12px;
    z-index: 9999;
}
</style>

toast/index.js 核心


import Toast from './Toast'
function install(Vue){
    // document.body.appendChild(Toast.$el) // $el => undefined

    // 1 创建组件构造器
    let ToastConstructor = Vue.extend(Toast)
    // 2 new 构造器 创建一个组件对象
    let newToast = new ToastConstructor()
    // 3 将组件对象手动挂载到某个元素上
    newToast.$mount(document.createElement('div'))
    // 4 newToast.$el 对应的 div
    document.body.appendChild(newToast.$el) 

    Vue.prototype.$toast = newToast
};

export default {install}

mian.js


import toast from 'components/common/toast'
// 安装toast插件
Vue.use(toast) // 会执行 toast.install 方法 会传递 Vue 构造函数

使用

this.$toast.show(' 添加成功')

在这里插入图片描述

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值