父组件:
<tempalte><view><toast ref="mytoast"></toast></view></template><script>methods:{func() {// 绑定子组件,调用子组件内的方法this.$refs.mytoast.showtoast( '成功' )}</script>
子组件:
<template><view class="container" v-if="Flag"><view class="content">{{content}}</view></view></template><script>//定时器标识timervar timer = nullexport default {name: "mytoast",data() {return {Flag: false,content: ''};},methods: {showtoast( val ) {this.content = val// 每次清除上一次timer,若无也没影响clearTimeout( timer )this.Flag= true// 添加定时器,1秒后消失timer = setTimeout( () => {this.Flag= false}, 1000 )}}}</script><style scoped>.container {color: white;padding: 20rpx 20rpx;background-color: rgb(77, 77, 77);border-top-left-radius: 5px;border-top-right-radius: 5px;border-bottom-left-radius: 5px;border-bottom-right-radius: 5px;position: absolute;left: 50%;top: 50%;transform: translate(-50%, -50%);}.content {width: 100%;height: 100%;display: flex;align-items: center;justify-content: center;}</style>
这里只是封装了一个功能很简单的showToast,有需要的话可以自己定义Toast出现的时间或者自行添加出现退出的动画效果。