美文网首页
写一个toast组件

写一个toast组件

作者: 杨晨1994 | 来源:发表于2020-04-17 15:04 被阅读0次

首先我们要知道我们这个toast组件是怎么调用的,一般来说都是全局的 类似于这样

this.$toast({
  content:'你好',
  duration:2000
}).show();

所以我们需要向vue的prototype 绑定一个$toast方法

import Vue from 'vue'
import toast from './component/toast'
Vue.prototype.$toast = toast;

我们的文件大概是这样的 一个js 一个vue文件


image.png
  • index.js
import Vue from 'vue';
import Toast from './index.vue'

export default function toast (props){ // 导出一个方法 方法接受一个参数
  const vm = new Vue({ // 生成一个vue实例
    render (h) { // 虚拟dom
      return h(Toast,{props})
    }
  }).$mount();// 创建一个组件实例 这里不能挂载到body上 必须手动append
  document.body.appendChild(vm.$el); // append 组件dom
  const comp = vm.$children[0]; // 获取实例内第一个组件 也就是toast.vue 因为就这一个
  comp.remove = function () { // 穿建一个销毁方法 避免内存泄漏
    document.body.removeChild(vm.$el);
    vm.$destroy()
  }
  return comp  // 最后我们吧这个组件return出去
}
  • index.vue
<template>
<div class="toastInfo" v-show="isShow">{{content}}</div>
</template>

<script>
  export default {
    name: "index",
    data () {
      return{
        isShow:false
      }
    },
    props:{
      content:{
        type:String,
        required:true
      },
      duration:{
        type:Number,
        default:1500
      }
    },
    methods:{
      show () {
        this.isShow = true;
        setTimeout(()=>{
          this.hide()
        },this.duration)
      },
      hide (){
        this.remove()
      }
    }
  }
</script>

<style lang="less" scoped>
.toastInfo{
  position: fixed;
  left: 50%;
  top: 10px;
  transform: translateX(-50%);
  background: rgba(0,0,0,0.5);
  color: #fff;
  padding: 5px 10px;
  border-radius: 2px;
}
</style>

相关文章

网友评论

      本文标题:写一个toast组件

      本文链接:https://www.haomeiwen.com/subject/ggxyvhtx.html