更新:登录功能
This commit is contained in:
16
hooks/usePageAuth.ts
Normal file
16
hooks/usePageAuth.ts
Normal file
@@ -0,0 +1,16 @@
|
||||
// hooks/usePageAuth.ts
|
||||
import { onShow } from '@dcloudio/uni-app'
|
||||
import { useUserStore } from '@/stores/user'
|
||||
|
||||
export function usePageAuth(redirect = '/pages/login/login') {
|
||||
const store = useUserStore()
|
||||
|
||||
onShow(() => {
|
||||
if (!store.token) {
|
||||
uni.showToast({ title: '请先登录', icon: 'none' })
|
||||
setTimeout(() => {
|
||||
uni.reLaunch({ url: redirect })
|
||||
}, 800)
|
||||
}
|
||||
})
|
||||
}
|
||||
35
hooks/useRequest.ts
Normal file
35
hooks/useRequest.ts
Normal file
@@ -0,0 +1,35 @@
|
||||
// hooks/useRequest.ts
|
||||
import { ref } from 'vue'
|
||||
|
||||
interface IUseRequestOptions<T> {
|
||||
immediate?: boolean
|
||||
initialData?: T
|
||||
}
|
||||
|
||||
export function useRequest<T>(
|
||||
func: () => Promise<T>,
|
||||
options: IUseRequestOptions<T> = { immediate: false },
|
||||
) {
|
||||
const loading = ref(false)
|
||||
const error = ref<any>(null)
|
||||
const data = ref<T | undefined>(options.initialData)
|
||||
|
||||
const run = async () => {
|
||||
loading.value = true
|
||||
error.value = null
|
||||
try {
|
||||
const res = await func()
|
||||
data.value = res
|
||||
return res
|
||||
} catch (err) {
|
||||
error.value = err
|
||||
throw err
|
||||
} finally {
|
||||
loading.value = false
|
||||
}
|
||||
}
|
||||
|
||||
options.immediate && run()
|
||||
|
||||
return { loading, error, data, run }
|
||||
}
|
||||
41
hooks/useUpload.ts
Normal file
41
hooks/useUpload.ts
Normal file
@@ -0,0 +1,41 @@
|
||||
// hooks/useUpload.ts
|
||||
import { ref } from 'vue'
|
||||
import { getAuthToken } from '@/utils/auth'
|
||||
|
||||
export function useUpload(uploadUrl: string) {
|
||||
const progress = ref(0)
|
||||
const uploading = ref(false)
|
||||
|
||||
const upload = (filePath: string) => {
|
||||
uploading.value = true
|
||||
return new Promise((resolve, reject) => {
|
||||
const uploadTask = uni.uploadFile({
|
||||
url: uploadUrl,
|
||||
filePath,
|
||||
name: 'file',
|
||||
header: {
|
||||
Authorization: `Bearer ${getAuthToken()}`,
|
||||
},
|
||||
success: (res) => {
|
||||
try {
|
||||
const data = JSON.parse(res.data)
|
||||
if (data.code === 200) resolve(data.data)
|
||||
else reject(data)
|
||||
} catch (e) {
|
||||
reject(e)
|
||||
}
|
||||
},
|
||||
fail: reject,
|
||||
complete: () => {
|
||||
uploading.value = false
|
||||
},
|
||||
})
|
||||
|
||||
uploadTask.onProgressUpdate((res) => {
|
||||
progress.value = res.progress
|
||||
})
|
||||
})
|
||||
}
|
||||
|
||||
return { progress, uploading, upload }
|
||||
}
|
||||
Reference in New Issue
Block a user