美文网首页
Vue自定义全局Toast组件

Vue自定义全局Toast组件

作者: Luciena | 来源:发表于2021-03-02 11:17 被阅读0次

背景:

在前端项目开发中,我们除了日常使用的vant库,还经常会根据业务自己去封装一些组件库。这样即会使得我们的代码可复用,又提高了我们的开发效率。

以最简化的Toast组件举例:

/components/toast.vue

<template lang="pug">
  .app(v-show='show')
    span {{ msg }}
</template>

<script>
export default {
  name: 'toast',
  props: {
    show: {
      type: Boolean,
      default: false
    },
    msg: {
      type: String,
      default: '提示'
    },
    duration: {
      type: Number,
      default: 2000
    }
  },
  data: {
    timerDuration: null
  },
  watch: {
    show(n) {
      if (!n && this.timerDuration) {
        clearTimeout(this.timerDuration)
        this.timerDuration = null
      }
    }
  },
  methods: {
    init() {
      this.show = true
      this.timerDuration = setTimeout(() => {
        this.show = false
      }, this.duration)
    },
    clear() {
      this.show = false
    }
  }
}
</script>

<style lang="scss" scoped>
.app {
  position: fixed;
  top: 50%;
  left: 50%;
  transform: translate(-50%, -50%);
  width: 160px;
  height: 40px;
  border-radius: 10px;
  background: rgba(0, 0, 0, 0.7);
  display: flex;
  align-items: center;
  justify-content: center;
  span {
    display: block;
    color: #fff;
    font-size: 14px;
  }
}
</style>

/common/toast.js

import Toast from '@/components/toast.vue'
let ConfirmConstructor, instance

const showToast = {
  install(Vue) {
    ConfirmConstructor = Vue.extend(Toast)
    instance = new ConfirmConstructor().$mount()
    document.body.appendChild(instance.$el)

    Vue.prototype.$showToast = options => {
      Object.assign(instance, options)
      instance.init()
    }
    Vue.prototype.$showToast.clear = () => {
      instance.clear()
    }
  }
}

export default showToast

/main.js

import ShowToast from './common/toast'
Vue.use(ShowToast)

/views/demo.vue

// 展示toast
this.$showToast({
  msg: '网络错误',
  duration: 1000
})

// 清除toast
this.$showToast.clear()

备注

基于上面最简化的demo,我们可以再丰富此组件亦可创造其他组件。

相关文章

  • 【vue3.0】10.0 某东到家(十)——Toast弹窗和代码

    全局的功能组件——自定义弹窗组件 新建src\components\Toast\Toast.vue: 修改src\...

  • vue 自定义组件(一)全局、局部组件

    vue自定义组件分为局部组件和全局组件 全局组件 全局组件格式template 是模板props 是自定义组件用到...

  • Vue自定义全局Toast组件

    背景: 在前端项目开发中,我们除了日常使用的vant库,还经常会根据业务自己去封装一些组件库。这样即会使得我们的代...

  • vue自定义组件

    vue自定义组件 1.vue全局组件 Vue.component("组件名",{obj});obj跟vue实例一样...

  • 2017.11.15

    Vue.prototypevue——自定义全局方法,在组件里面使用 Vue.prototype 不是全局变量,而...

  • Vue组件(compoent)

    自定义组件有两种方式1.全局组件,2.局部组件 全局组件:我们可以这样理解,一个vue组件就是一个vue实例 组件...

  • 封装toast插件

    toast.vue toast.js **全局调用$toast方法就是触发了绑定在Vue原型上的showToast...

  • vue写的todolist框

    Toast 点击框框 var a = Vue.component('Toast',{//定义组件 templa...

  • Vue2.0的改变

    vue2.0-组件定义方式 全局 局部 生命周期 组件2.0循环 自定义键盘 单一事件中心管理组件通信 vue2....

  • vue中自定义组件、指令、插件

    组件 全局组件 局部组件 自定义插件 提供install方法,挂载到Vue 指令 使用指令实现input自动获取焦...

网友评论

      本文标题:Vue自定义全局Toast组件

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