关于在vue3组合式API中使用异步函数获取响应式数据的问题?

作者站长头像
站长
· 阅读数 8

为了代码复用,我并没有在setup钩子中定义getUserInfo异步函数,其中异步函数中已经定义了响应式对象userInfo,并返回了这个userInfo 但是该函数返回的是一个promise,我在setup中使用该对象还需要await一下,有没有更好的办法可以在setup之外定义该函数,并在使用时不需要await

<script type="module">
    const { createApp, ref,reactive } = Vue
    import Card from '../../Content/Components/Card.js'
    const app = createApp({
        components: {
            Card
        },
        setup() {
            const active = ref('gongzuotai')
            const onClickLeft = () => history.back()
            //用户信息
            **const userInfo = getUserInfo()**
            console.log(userInfo,'响应式数据')
            return {
                active,
                onClickLeft,
                userInfo
            }
        },
      

    });
    //获取用户信息
    async function getUserInfo() {
        let userInfo = reactive({})
        const today = new Date();
        const year = today.getFullYear();
        const month = (today.getMonth() + 1).toString().padStart(2, '0');
        const date = '01';
        const monthStr = `${year}-${month}-${date}`;
        const yearStr = `${year}-01-${date}`;
        const res = await axios.get('GetUserInfo', {
            params: {
                month: monthStr,
                year: yearStr
            }
        })
        userInfo = JSON.parse(res.data.data)[0]
        console.log(userInfo)
        return userInfo

    }
    app.use(vant)
    app.mount('#app');

</script>
回复
1个回答
avatar
test
2024-07-02

可以考虑使用 hooks

// useUserInfo.js

export const useUserInfo = () => {
    const userInfo = ref({})
    const getUserInfo = async () => {
        const res = await axios.get('GetUserInfo', {
            params: {
                month: monthStr,
                year: yearStr
            }
        })
        userInfo.value = JSON.parse(res.data.data)[0]
    }
    return {
        userInfo,
        getUserInfo
    }
}


// xx.vue
<script setup>
import { useUserInfo } from 'useUserInfo'
const { userInfo, getUserInfo } = useUserInfo()
getUserInfo()
</script>
回复
likes
适合作为回答的
  • 经过验证的有效解决办法
  • 自己的经验指引,对解决问题有帮助
  • 遵循 Markdown 语法排版,代码语义正确
不该作为回答的
  • 询问内容细节或回复楼层
  • 与题目无关的内容
  • “赞”“顶”“同问”“看手册”“解决了没”等毫无意义的内容