温馨提示×

温馨提示×

您好,登录后才能下订单哦!

密码登录×
登录注册×
其他方式登录
点击 登录注册 即表示同意《亿速云用户服务条款》

Vue中Toast的示例分析

发布时间:2021-08-19 10:30:34 来源:亿速云 阅读:414 作者:小新 栏目:web开发

这篇文章将为大家详细讲解有关Vue中Toast的示例分析,小编觉得挺实用的,因此分享给大家做个参考,希望大家阅读完这篇文章后可以有所收获。

一、效果图

Vue中Toast的示例分析

二、说明

这类提示框组件我们通常都会直接在 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原型上,如下图:

Vue中Toast的示例分析

其次,在代码中使用

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

关于“Vue中Toast的示例分析”这篇文章就分享到这里了,希望以上内容可以对大家有一定的帮助,使各位可以学到更多知识,如果觉得文章不错,请把它分享出去让更多的人看到。

向AI问一下细节

免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。

AI