当前位置: 移动技术网 > IT编程>脚本编程>vue.js > Vue组件教程之Toast(Vue.extend 方式)详解

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

2019年05月28日  | 移动技术网IT编程  | 我要评论

蜗居2鲜花朵朵,gogo tester,2016考研英语一答案

一、效果图

二、说明

这类提示框组件我们通常都会直接在 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('别点啦,到头啦!')

总结

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

如对本文有疑问,请在下面进行留言讨论,广大热心网友会与你互动!! 点击进行留言回复

相关文章:

验证码:
移动技术网