Vue 封装Toast提示框

2021-11-04  本文已影响0人  香蕉不拿呢
场景:在Vue中使用类似App的Toast提示框。·
使用: this.$myToast({text:'你好',duration:1500});
效果:
效果
文件 toast文件夹下两个文件分别为:index.js与index.vue
> │└─toast
> │      index.js
> │      index.vue
index.vue
// vue封装组件  使用transition标签实现淡入淡出效果
<template>
    <div>
        <transition name="my-in-out">
            <div v-show="show" class="my-toast">
                {{text}}
            </div>
        </transition>
    </div>
</template>
<script lang="ts">
import Vue from 'vue'
export default Vue.extend({
    data(){
        return {
            show: true,
            text: 'hellow world'
        }
    },
})
</script>
<style scoped>
    .my-toast {
        position: fixed;
        z-index: 2021;
        left: 50%;
        top:45%;
        transition:all .5s;
        transform: translateX(-50%) translateY(-50%);
        text-align: center;
        border-radius: 5px;
        color:#FFF;
        background: rgba(17, 17, 17, 0.7);
        font-size: 20px;
        padding: 20px 35px;
    }
    .my-in-out-enter,.my-in-out-leave-to{
        opacity: 0;
    }
    .my-in-out-enter-to,.my-in-out-leave{
        opacity: 1;
    }
    .my-in-out-enter-active,.my-in-out-leave-active{
        transition: all 1s;
    }
</style>
index.js
//   这里使用闭包保存变量
let _myToast = {
    show : false,  
    component : null
}
import Component from './index.vue'

export default {
    install(Vue){
        Vue.prototype.$toast = function(options){
            let _options = {
                duration: 1500,
                text:'hello word'
            }
            Object.assign(_options,options);
            if(_myToast.show){    // 节流 防止频繁触发
                return;
            }
            if(!_myToast.component){
                _myToast.component = new Component();
                let element = _myToast.component.$mount().$el
                document.body.appendChild(element)
            }
            _myToast.component.text = _options.text;
            _myToast.component.show = _myToast.show = true;
            setTimeout(()=>{
                _myToast.component.show = _myToast.show = false;
            },_options.duration)
        }
    }
}
在main.ts中引用安装
// Vue.use()会自动调用导出的install方法
import Vue from 'vue'
import App from './App.vue'
import router from './router'
import store from './store'
import Toast from './components/toast/index.js'

Vue.config.productionTip = false
Vue.use(Toast)

new Vue({
  router,
  store,
  render: h => h(App)
}).$mount('#app')

使用
<template>
  <div class="test">
    <button @click="showToast">show</button>
  </div>
</template>
<script lang="ts">
import Vue from 'vue'
export default Vue.extend({
  methods:{
    showToast(){
      this.$toast({
          text : '你好',
          duration : 3000
        })
    }
  }
})
</script>
上一篇 下一篇

猜你喜欢

热点阅读