toast-mixin.js 1.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475
  1. /**
  2. * Toast 全局 Mixin
  3. * 在 main.js 中通过 Vue.mixin 注入到所有页面
  4. *
  5. * 使用方式:
  6. * - 在页面 template 中添加 <ay-toast ref="ayToast" />
  7. * - 在页面 methods 中使用 this.$toast.success('提示')
  8. */
  9. export default {
  10. methods: {
  11. /**
  12. * 获取 $toast 实例代理
  13. * 通过 this.$refs.ayToast 获取组件实例
  14. */
  15. $toast(options) {
  16. const ref = this.$refs.ayToast
  17. if (ref) {
  18. ref.show(options)
  19. } else {
  20. // 降级:通过全局事件通知
  21. uni.$emit('ayToast:show', typeof options === 'string' ? { type: 'text', title: options } : options)
  22. }
  23. }
  24. },
  25. computed: {
  26. /**
  27. * 提供 this.$toastRef 快捷访问
  28. */
  29. $toastRef() {
  30. return {
  31. success: (title, options = {}) => {
  32. const ref = this.$refs.ayToast
  33. if (ref) {
  34. ref.success(title, options)
  35. } else {
  36. uni.$emit('ayToast:show', { type: 'success', title, duration: 2000, ...options })
  37. }
  38. },
  39. error: (title, options = {}) => {
  40. const ref = this.$refs.ayToast
  41. if (ref) {
  42. ref.error(title, options)
  43. } else {
  44. uni.$emit('ayToast:show', { type: 'error', title, duration: 2500, ...options })
  45. }
  46. },
  47. loading: (title = '加载中...', options = {}) => {
  48. const ref = this.$refs.ayToast
  49. if (ref) {
  50. ref.loading(title, options)
  51. } else {
  52. uni.$emit('ayToast:show', { type: 'loading', title, duration: 0, mask: true, ...options })
  53. }
  54. },
  55. text: (title, options = {}) => {
  56. const ref = this.$refs.ayToast
  57. if (ref) {
  58. ref.show({ type: 'text', title, duration: 2000, ...options })
  59. } else {
  60. uni.$emit('ayToast:show', { type: 'text', title, duration: 2000, ...options })
  61. }
  62. },
  63. hide: () => {
  64. const ref = this.$refs.ayToast
  65. if (ref) {
  66. ref.hide()
  67. } else {
  68. uni.$emit('ayToast:hide')
  69. }
  70. }
  71. }
  72. }
  73. }
  74. }