vue 支持频繁调用的toast demo

实现功能:一个 Toast 组件,显示一段传入文本,2s 后自动消失。如果多次调用,显示最后一次的内容,同样2s后消失。
基于vue实现的一个toast demo
核心代码:
一个vue组件

<template>
    <div class="toast" v-if="show">
       {{msg}}
    </div>
</template>
<script>
export default {
    data() {
        return {
            msg: '',
            show: false,
            t: null
        }
    }, 
    methods: {
        showToast(msg) {
                this.msg = msg
                if (this.show) {
                    clearTimeout(this.t)
                    this.t = setTimeout(()=>{
                        this.show = false
                    }, 2000)      
                    return              
                }
                this.show = true
                this.t = setTimeout(()=>{
                    this.show = false
                }, 2000)
        }
    }
}
</script>
<style lang="less" scoped>
.toast {
    position: fixed;
    bottom: 100px;
    width: 300px;
    height: 80px;
    margin: auto;
    right: 0;
    left: 0;
    text-align: center;
    font-size: 16px;
    color: #fff;
    line-height: 80px;
    background-color: #000;
}
</style>

使用插件的方式对这个vue组件进行初始化,方便调用

import toast from './pages/toast.vue'
export default {
    install(vue) {
        let toastComponent = vue.extend(toast)
        const vm = new toastComponent(
            {el: document.createElement('div')}
        )
        document.getElementsByTagName('body')[0].appendChild(vm.$el)
        vue.prototype.$toast = {
            showToast: function(msg) {
                vm.showToast(msg)
            }
        }
    }
}

在入口js对插件进行注册,就可以了

Vue.use(toast)

效果截图:


image.png

github地址:https://github.com/hellofriday/vue-toast-demo

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。