美文网首页
vue自定义Toast插件

vue自定义Toast插件

作者: 十年之后_b94a | 来源:发表于2020-07-02 14:20 被阅读0次

创建toast模板

<template>
  <transition name="alert-fade">
    <div id="toast"
         v-show="visible"
         class="dialog-tips dialog-center">
      {{message}}
    </div>
  </transition>
</template>
<script>
export default {
  data () {
    return {
      visible: false,
      message: ''
    }
  }
}
</script>
<style lang="stylus" scoped>
.alert-fade-enter-active,
.alert-fade-leave-active {
  transition: opacity 0.3s;
}
.alert-fade-enter,
.alert-fade-leave-to {
  opacity: 0;
}
.dialog-tips {
  position: fixed;
  z-index: 100;
  min-width: 100px;/*no */
  padding: 15px;/*no */
  border-radius: 15px;/*no */
  white-space: nowrap;
  background-color: rgba(0,0,0,1);
  box-shadow: 0px 8px 30px 0 rgba(0, 0, 0, 0.363);/*no */
  text-align: center;
  color: #fff;
  font-size: 15px/*no */
}
.dialog-center {
  top: 20%;
  left: 50%;
  transform: translate(-50%, -50%);
}
</style>

通过 Vue.extend() 扩展模板

import fyChatToast from './fyChatToast.vue'
const toast = {}
toast.install = Vue => {
    // 扩展 vue 插件
    const ToastCon = Vue.extend(fyChatToast)
    const ins = new ToastCon()
    // 挂载 dom
    ins.$mount(document.createElement('div'))
    // 添加到 body 后面
    document.body.appendChild(ins.$el)
    // 给 vue 原型添加 toast 方法
    Vue.prototype.$toast = (msg, duration = 3000) => {
        // 我们调用的时候 赋值 message
        // 将 visible 设置为 true
        // 默认 3s 之后 设置 为 false 关闭 toast
        ins.message = msg
        ins.visible = true
        setTimeout(() => {
            ins.visible = false
        }, duration)
    }
}
export default toast

挂在实例

main.js

import toast from '@/components/Toast/index'
Vue.use(toast);

相关文章

网友评论

      本文标题:vue自定义Toast插件

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