Vue组件教程之Toast(Vue.extend 方式)详解

一、效果图

二、说明

这类提示框组件我们通常都会直接在 JS 代码中进行调用。像下面这样:

this.$toast('别点啦,到头啦!')

但看到网上大多数还是通过 component 方式实现的,这样的话我们在使用的时候还要在 DOM 中放置一个组件元素,然后通过一个变量来控制它的显示隐藏,这样使用起来非常的不方便。那么有什么方法可以不用在 DOM 中手动放置组件元素就可以直接调用呢?答案就是 Vue.extend。通过 Vue.extend 方式实现的组件,需要两个文件,一个是 .vue 文件,另外一个就是管理 .vue 的 .js 文件。具体代码如下:

三、代码

Toast.vue 文件代码

<template>
 <div class="toast" v-show="visible">
 {{ message }}
 </div>
</template>

<script>
export default {
 name: 'toast',
 data () {
 return {
  message: '', // 消息文字
  duration: 3000, // 显示时长,毫秒
  closed: false, // 用来判断消息框是否关闭
  timer: null, // 计时器
  visible: false // 是否显示
 }
 },
 mounted () {
 this.startTimer()
 },
 watch: {
 closed (newVal) {
  if (newVal) {
  this.visible = false
  this.destroyElement()
  }
 }
 },
 methods: {
 destroyElement () {
  this.$destroy()
  this.$el.parentNode.removeChild(this.$el)
 },
 startTimer () {
  this.timer = setTimeout(() => {
  if (!this.closed) {
   this.closed = true
   clearTimeout(this.timer)
  }
  }, this.duration)
 }
 }
}
</script>

<style lang="scss" scoped>
.toast {
 position: fixed;
 bottom: 15vh;
 left: 28vw;
 min-width: 40vw;
 max-width: 100vw;
 font-size: 26px;
 text-align: center;
 padding: 10px 2vw;
 border-radius: 40px;
 background-color: rgba(0, 0, 0 , 0.6);
 color: rgb(223, 219, 219);
 letter-spacing: 3px;
}
</style>

Toast.js 文件代码

import Vue from 'vue'
import Toast from '@/components/layer/Toast.vue'

let ToastConstructor = Vue.extend(Toast) // 构造函数
let instance // 实例对象
let seed = 1 // 计数

const ToastDialog = (options = {}) => {
 if (typeof options === 'string') {
 options = {
  message: options
 }
 }
 let id = `toast_${seed++}`
 instance = new ToastConstructor({
 data: options
 })
 instance.id = id
 instance.vm = instance.$mount()
 document.body.appendChild(instance.vm.$el)
 instance.vm.visible = true
 instance.dom = instance.vm.$el
 instance.dom.style.zIndex = 999 + seed
 return instance.vm
}

export default ToastDialog

四、使用

首先在 main.js 中引入 Toast.js 并挂载到vue原型上,如下图:

其次,在代码中使用

this.$toast('别点啦,到头啦!')

总结

以上就是这篇文章的全部内容了,希望本文的内容对大家的学习或者工作具有一定的参考学习价值,如果有疑问大家可以留言交流,谢谢大家对呐喊教程的支持。

声明:本文内容来源于网络,版权归原作者所有,内容由互联网用户自发贡献自行上传,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任。如果您发现有涉嫌版权的内容,欢迎发送邮件至:notice#nhooo.com(发邮件时,请将#更换为@)进行举报,并提供相关证据,一经查实,本站将立刻删除涉嫌侵权内容。