美文网首页
对象赋值响应式

对象赋值响应式

作者: 蓝蓝红同学 | 来源:发表于2022-11-08 15:14 被阅读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!)
    })
    

    相关文章

      网友评论

          本文标题:对象赋值响应式

          本文链接:https://www.haomeiwen.com/subject/acjntdtx.html