对象赋值响应式

2022-11-08  本文已影响0人  蓝蓝红同学

vue3,reactive对象在赋值后,变量代理函数变了,失去了响应式

解决方案

使用Object.assign()

import topic from '../../../components/topic.vue'
import { onLoad } from '@dcloudio/uni-app'
import { getTopicInfo } from '../../../api/topic'
import { ref, reactive, watch } from 'vue'
let topicInfo = reactive({})
const getTopicDetail = async (id: string) => {
  const res: any = await getTopicInfo({ topicId: id })
// topicInfo = res.data.data // 会失去响应式,视图不更新
// topicInfo = {...res.data.data}  // 解构赋值一样会导致topicInfo失去响应式,视图不更新
  Object.assign(topicInfo, res.data.data)  // 合并对象,仍指向原引用地址
}
onLoad((option) => {
  getTopicDetail(option.topicId!)
})

使用ref

import topic from '../../../components/topic.vue'
import { onLoad } from '@dcloudio/uni-app'
import { getTopicInfo } from '../../../api/topic'
import { ref, reactive, watch } from 'vue'
let topicInfo = ref({})
const getTopicDetail = async (id: string) => {
  const res: any = await getTopicInfo({ topicId: id })
    topicInfo.value = res.data.data
}
onLoad((option) => {
  getTopicDetail(option.topicId!)
})
上一篇下一篇

猜你喜欢

热点阅读