如何使用flexible的Vue组件Toast显示框

2023-06-12,,

这篇文章将为大家详细讲解有关如何使用flexibleVue组件Toast显示框,小编觉得挺实用的,因此分享给大家做个参考,希望大家阅读完这篇文章后可以有所收获。

Toast -- 显示框

效果展示

 

代码分析

div包含icon小图标和文字说明,构成简单的dom结构,利用props定义变量值,用computed计算属性对传入的值进行解构,watch监听弹框显示,并结合.sync修饰符达到双向数据绑定,同时用$emit向父组件派发事件,方便父组件监听回调。

dom结构

<transition name="fade">
 <div class="Toast" v-if="toastShow">
 <div
 class="box"
 :
 >
 <span
 :class="iconClass"
 :
 v-if="iconIsShow"
 ></span>
 <p
 v-if="message"
 >{{message}}</p>
 </div>
 </div>
</transition>

props数据

props: {
 message: { // 提示内容
 type: String,
 },
 toastShow: { // 是否显示
 type: Boolean,
 default: false
 },
 iconClass: { // 背景图片
 type: String,
 },
 iconImage: { // 自定义背景图片
 },
 duration: { // 定时器
 type: Number,
 default: 1500
 },
 position: { // 弹出框位置
 type: String,
 default: '50%'
 }
},

computed

computed: {
 // 用于判断显示框位置
 positionTop() {
 return {
 top: this.position
 }
 },
 // 自定义父组件传过来的背景图片
 iconBg() {
 if (this.iconImage) {
 return {
 backgroundImage: `url(${this.iconImage})`
 }
 } else {
 return;
 }
 },
 // 用于判断icon是否显示
 iconIsShow() {
 if (this.iconClass == 'success') {
 return true;
 } else if (this.iconClass == 'close') {
 return true;
 } else if (this.iconClass == 'warning') {
 return true;
 } else if (this.iconImage) {
 return true;
 } else {
 return false;
 }
 }
},

watch

watch: {
 toastShow() {
 // 监听toast显示,向父组件派发事件
 if (this.toastShow) {
 if (this.duration < 0) {
 this.$emit('toastClose');
 } else {
 setTimeout(()=>{
  this.$emit('update:toastShow', false) // 利用了.sync达到双向数据绑定
  this.$emit('toastClose');
 }, this.duration)
 }
 }
 }
}

使用说明

组件地址: src/components/Toast.vue (不能npm,只能手动下载使用)

下载并放入自己项目中 —— import 引入组件 —— components中注册组件 —— 使用

props

props 说明 类型 可选值 默认值
toastShow 控制显示框显示、隐藏。需添加.sync修饰符才能自动关闭,详见例子 Boolean false 
 true
false
message 提示信息 String
iconClass icon小图标 String success 
 warning 
 close
iconImage 自定义小图标(图片需require引入)
duration 定时器(毫秒),控制弹框显示时间,负数代表不执行定时任务 Number 1500
position 弹框位置(距顶) String '50%'

$emit

$emit 说明 参数
toastClose 弹框关闭回调

示例

// 默认效果,只有提示信息
 <toast
 message = '默认信息'
 :toastShow.sync = 'isShow1' // 需添加.sync修饰符,才能达到自动关闭的效果,否则只能监听toastClose手动关闭
 ></toast>  // 关于sync的说明,请看官网(主要是为了达到双向数据绑定,子组件修改父组件状态)
 
 // 增加自带小图标
 <toast
 message = 'success'
 iconClass = 'success'
 :toastShow.sync = 'isShow2'
 ></toast>
// 自定义类型
 <toast
 message = '自定义'
 position = '70%'
 :duration = '-1' //负数代表不执行定时任务,自己根据需要去关闭
 :iconImage='bg' // 自定义icon小图标,在data中需require引入,看下面
 :toastShow = 'isShow5' // 因为需要手动关闭,所以不需要.sync了
 @toastClose = 'isClose5' // 监听回调,手动关闭,看下面
 ></toast>
 
 data() {
 return {
 this.isShow5 : true,
 bg: require('../assets/logo.png'), // 图片必须用require进来
 }
 },
 isClose5() {
 setTimeout(()=>{
 this.isShow5 = false;
 }, 2000)
 }

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

《如何使用flexible的Vue组件Toast显示框.doc》

下载本文的Word格式文档,以方便收藏与打印。