how can I get data property from ref object in vue3

Viewed 1124

First I create a ref object named teamData, then fetch service api and assign to teamData.

But what should I do get data property from teamData. for example I want to get title property from teamData, but result is unxexpected

here is the code

// 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

1 Answers

It looks like it's a lifecycle issue, because the code inside the setup hook is ran before the code inside onMounted hook, to solve this try out to use a 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
  })
Related