Vue组件教程之Toast(Vue.extend 方式)详解
网络编程 2021-07-04 15:50www.168986.cn编程入门
这篇文章主要给大家介绍了关于Vue组件教程之Toast(Vue.extend 方式)的相关资料,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友们狼蚁网站SEO优化随着长沙网络推广来一起学习学习吧
一、效果图
二、说明
这类提示框组件我们通常都会直接在 JS 代码中进行调用。像狼蚁网站SEO优化这样:
this.$toast('别点啦,到头啦!')
但看到网上大多数还是通过 ponent 方式实现的,这样的话我们在使用的时候还要在 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 '@/ponents/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('别点啦,到头啦!')
总结
以上就是这篇文章的全部内容了,希望本文的内容对大家的学习或者工作具有一定的参考学习价值,如果有疑问大家可以留言交流,谢谢大家对狼蚁SEO的支持。
上一篇:vue中轮训器的使用
下一篇:JavaScript变量提升和严格模式实例分析
编程语言
- 机械手焊接机器人编程 机械手焊接设备编程
- vb数据库编程实例,vb做数据库
- tiobe世界编程语言排行榜,全球编程语言排行
- 成都java编程培训 成都it编程培训中心
- 编程基础培训,编程基础知识培训
- flash游戏编程基础教程,flash游戏开发教程
- 不会英语能学编程吗 不会英语可以学程序员吗
- 爱心代码编程C语言 爱心代码编程c语言公式
- c语言编程学习入门 c语言编程快速入门
- 西门子plc编程培训 西门子plc编程培训班
- 哪里可以学编程 台州哪里可以学编程
- 少儿编程哪个好 少儿编程哪个品牌好
- 编程是什么意思,图形编程是什么意思
- c语言编程软件下载,c语言编程软件在哪下载
- java编程软件下载,java编程下载手机版
- ug编程培训学校,ug编程培训教程