gpt4 book ai didi

javascript - 如何从 vue3 中的 ref 对象获取数据属性

转载 作者:行者123 更新时间:2023-12-04 07:14:20 25 4
gpt4 key购买 nike

首先我创建一个名为 teamData 的 ref 对象,然后获取服务 api 并分配给 teamData。
但是我该怎么做才能从 teamData 获取数据属性。例如我想从 teamData 获取 title 属性,但结果出乎意料
这是代码

// useTeamData.js
import { fetchTeamGoal } from '@/api/team'
import { onMounted, watch, ref} from 'vue'

export default function getTeamData(date) {
const teamData = ref({})
const getTeamGoals = async () => {
await fetchTeamGoal(date.value + '-01').then(res => {
teamData.value = res.data
})
}
onMounted(getTeamGoals)
watch(date, getTeamGoals)
return {
teamData,
getTeamGoals
}
}
// test.vue
import dayjs from 'dayjs'
import useTeamData from '@/components/composables/useTeamData'
import {defineComponent, ref, toRefs, computed, provide, toRaw, reactive} from 'vue'
import { useStore } from 'vuex'

export default defineComponent({
name: 'Test',
setup: () => {
const store = useStore()
const userInfo = computed(() => store.state.user.userInfo)
const date = ref(dayjs().format('YYYY-MM'))
const { teamData } = useTeamData(date)
console.log(teamData, 'teamData')
console.log(teamData.title)
console.log(teamData.value.title)

provide('role', userInfo.value.role)
return {
date,
userInfo,
teamData,
}
},
})
here is the browser output image

最佳答案

看起来这是一个生命周期问题,因为 setup hook 中的代码在 onMounted 中的代码之前运行 Hook ,要解决此问题,请尝试使用 watch :

import {defineComponent,watch, ref, toRefs, computed, provide, toRaw, reactive} from 'vue'
...
const { teamData } = useTeamData(date)

watch(()=>teamData,(newVal,oldVal)=>{
console.log(newVal.value.title)
},
{
deep:true,
immediate:true
})

关于javascript - 如何从 vue3 中的 ref 对象获取数据属性,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/68879304/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com