在项目中可能有多个页面会使用到相同的方法,每个页面单独写一份既增加了重复的代码量又不利于后期的维护,这时候我们就可以将相同的方法抽成一个共用函数,只要在对应的页面进行调用就可以了,按需传入自己需要的参数。
// 将需要共用的函数放到共用文件夹中并导出,在对应页面直接导入即可
export function sharedFunction(str = '', arr = [], obj = {}, saveFunction = () => {}) {
interfaceCall({ strInfo: str }).then(res => {
if (!res.data) {
const haveSome = arr.filter(item => item.xxx === obj.xxx)
const tipInfo = []
if (haveSome.length > 0) {
tipInfo.push('提示语')
}
if (tipInfo.length > 0) {
// 这里不能直接用this,要改用Vue.prototype
Vue.prototype.$confirm(`${tipInfo.join(',')}`, '提示', {
confirmButtonText: '确定',
cancelButtonText: '取消',
type: 'warning'
}).then(() => {
// 可以通过调用形参去执行实参里接下来的逻辑
saveFunction()
})
} else {
saveFunction()
}
} else {
saveFunction()
}
})
}
otherFun(str = '', obj = {}) {
// 对应页面进行其他逻辑的函数
}
// 在对应页面进行函数调用以及传参
sharedFunction('字符串',
['1', '2', '3'],
{name: 'zhangsan', age: 18},
() => {
this.otherFun('字符串', {name: 'lisi'})
}
)
以及可以写成mixin
vue中的minix