前言
应用开发中,提取公用函数全局调用,避免每个页面都写函数或者每次都得重新引用。比如:打开新页面、返回页面、toast提示信息等。
实现
- 定义函数
- 在main.js中注册
- 在页面中引用
具体演示代码
1、定义函数,文件yjUtil.js中:
/**
* 消息弹窗
* @author yj
*
* @param {String} title: 标题
* @param {String} icon: toast显示的图标, 可选值: success/error/fail/exception/loading/none
* @param {Number} duration: 窗口动画持续时间, 单位为ms
*/
const toast = (title, icon = 'none', duration = 2000) => {
uni.showToast({
title,
duration,
icon
});
}
/**
* 保留当前页面,跳转到应用内的某个页面
* @author yj
*
* @param {String} url: 需要跳转的应用内非 tabBar 的页面的路径
* @param {String} animationType: 窗口显示的动画效果
* @param {Number} animationDuration: 窗口动画持续时间,单位为 ms
*/
const goto = (url, animationType = 'pop-in', animationDuration = 300) => {
uni.navigateTo({
url,
animationType,
animationDuration,
success: function(res) {},
fail: function(e) {}
})
}
/**
* 关闭当前页面,返回上一页面或多级页面
* @author yj
*
* @param {String} url: 需要跳转的应用内非 tabBar 的页面的路径
* @param {String} animationType: 窗口显示的动画效果
* @param {Number} animationDuration: 窗口动画持续时间,单位为 ms
*/
const goback = (delta = 1, animationType = 'pop-out', animationDuration = 300) => {
let pages = getCurrentPages();
if (pages.length < delta) {
delta = pages.length - 1
}
if (pages.length == 1) {
return
}
uni.navigateBack({
delta,
animationType,
animationDuration,
success: function(res) {},
fail: function(e) {}
})
}
//注册定义的方法
export const yjUtil = {
toast,
goto,
goback
}
2、全局注册,在main.js中全局注册
// main.js
import {yjUtil} from './common/yjUtil.js'
Vue.prototype.$yjUtil=yjUtil;
3、页面中使用
// 页面中使用
this.$yjUtil.goto('/pages/index/index') // 页面跳转
this.$yjUtil.goback(2) // 页面返回 2 层
this.$yjUtil.goback() // 页面返回 1 层
this.$yjUtil.toast('已修改','success') // 消息弹窗
this.$yjUtil.toast('加载失败') // 消息弹窗