制作一个简单的toast弹框

toast弹框的作用

  • toast弹框顾名思义,就是为了弹出一个提示框,效果如图:

image-20210119173020523

  • 使用toast弹框可以可用户带来更好的交互体验

toast弹框的使用

  • Toast组件
    • 制做出toast的样式以及出现的条件
<template>
  <div class="toast" v-show="isShow">
    <div>{{message}}</div>
  </div>
</template>

<script>
  export default {
    name: 'Toast',
    data() {
      return {
        message: '',
        isShow: false
      }
    },
    methods: {
      // 通过调用该方法可以设置弹框信息以及弹框持续的时间
      show(message = '默认文字', duration = 2000) {
        this.isShow = true
        this.message = message
        setTimeout(() => {
          this.isShow = false
          this.message = ''
        }, duration)
      }
    }
  }
</script>

<style scoped>
  .toast {
    position: fixed;
    top: 50%;
    left: 50%;
    color: #fff;
    z-index: 999;
    padding: 8px 10px;
    transform: translate(-50%, -50%);
    background-color: rgba(0, 0, 0, 0.7);
  }
</style>
  • 在vue原型上添加toast
    • 将toast元素挂载到body上
//index.js
import Toast from './Toast'
const obj = {}

// install 是默认的方法。当外界在 use 这个组件的时候,就会调用本身的 install 方法(对外暴露一个install方法即可),同时传一个 Vue 这个类的参数。
obj.install = function(Vue) {
  // 1.创建组件构造器
  const ToastConstructor = Vue.extend(Toast)
  // 2.news的方式,根据组件构造器,可以创建出来一个组件对象
  const toast = new ToastConstructor()
  // 3.将组件对象手动的挂载到某个一个元素上,此时,toast.$el对应的就是div了
  toast.$mount(document.createElement('div'))
  // 4.将这个div作为body的子元素添加进去
  document.body.appendChild(toast.$el)
  // 5.将toast对象作为vue的原型属性,便于之后的调用
  Vue.prototype.$toast = toast
}
export default obj
  • 在main中安装toast插件
import toast from 'components/common/toast/index.js'

// 安装toast(吐司)插件,用于弹出一个提示
Vue.use(toast)
  • 使用toast弹框
this.$toast.show(res, 1500)
posted @ 2021-01-31 15:32  journey-of-dreams  阅读(431)  评论(0编辑  收藏  举报