写一个toast组件

首先我们要知道我们这个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>

©著作权归作者所有,转载或内容合作请联系作者
【社区内容提示】社区部分内容疑似由AI辅助生成,浏览时请结合常识与多方信息审慎甄别。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

相关阅读更多精彩内容

  • 1. vue-cli 构建项目 官网地址[https://cn.vuejs.org/v2/guide/insta...
    sunxiaochuan阅读 17,212评论 6 103
  • 基于Vue的一些资料 内容 UI组件 开发框架 实用库 服务端 辅助工具 应用实例 Demo示例 element★...
    尝了又尝阅读 1,275评论 0 1
  • UI组件 element - 饿了么出品的Vue2的web UI工具套件 Vux - 基于Vue和WeUI的组件库...
    卞卞村长L阅读 1,867评论 0 8
  • Vue2.0+组件库总结 UI组件 element - 饿了么出品的Vue2的web UI工具套件 Vux - 基...
    szch阅读 2,045评论 1 52
  • 响应式布局的理解 响应式开发目的是一套代码可以在多种终端运行,适应不同屏幕的大小,其原理是运用媒体查询,在不同屏幕...
    懒猫_6500阅读 851评论 0 0

友情链接更多精彩内容