自定义useLocation
模拟获取一个地理位置
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
import {reactive, onMounted, toRefs } from 'vue';
// 模拟异步获取
function getLocation(fail) {
debugger
return new Promise(resolve => {
setTimeout(() => {
if (fail) {
resolve({errno: 1, msg: fail})
} else {
resolve({errno: 0, data: { x: 100, y: 200}})
}
}, 1000)
})
}
function useLocation() {
debugger
const info = reactive({
isLoadingRef: true,
data: {},
errMsg: ''
})
onMounted(async () => {
const res = await getLocation()
debugger
if (res.errno === 0) {
info.data = res.data
} else {
info.errMsg = res.msg
}
info.isLoadingRef = false
})
return toRefs(info)
}
export default useLocation
引用如下
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
<template>
<div>::</div>
</template>
<script >
import useLocation from 'useLocation.js'
export default {
// 在选项组件中使用Composition API
setup() {
const { isLoadingRef, data, errMsg } = useLocation()
// const useLocation = useLocation()
return { isLoadingRef, data, errMsg }
},
mounted(){
}
}
</script>