Vue3 reactive响应式重新赋值问题
场景:父组件传值子组件,用reactive定义的属性,父组件等待接口返回数据后重新赋值,子组件无法读取
子组件中接收props
const props = defineProps({ commentlist: { type: Array, default() { return [] } } })
方法一、利用ref替换reactive响应式
父组件声明:
let commentlist = ref() const getComments = async () => { const result = await fetch('/comments/list') if (result.status === 1) { console.log('commentlist',commentlist); commentlist.value = result.commentlist commentlist.value[0].starNum = 100 } } getComments()
子组件中使用:
<div class="commentBox" v-for="v in props.commentlist" :key="v.id">
<div class="info">
<span class="comment">{{v.comment}}</span>
<div class="starBox">
<span style="margin:0 6px">{{v.starNum}}</span>
<like-outlined />
</div>
<div class="downBox">
<span style="margin:0 6px">{{v.downNum}}</span>
<like-outlined :rotate='180' />
</div>
</div>
<p class="user"><span>{{v.username}}</span><span>{{v.createTime}}</span></p>
</div>
通过ref响应式 xxx.value获取数据
方法二:reactive声明包裹到对象中
父组件声明:
let commentlist = reactive({ data: [] }) const getComments = async () => { const result = await fetch('/comments/list') if (result.status === 1) { commentlist.data = result.commentlist commentlist.data[0].starNum = 100 } } getComments()
子组件中使用:
<div class="commentBox" v-for="v in props.commentlist.data" :key="v.id"> <div class="info"> <span class="comment">{{v.comment}}</span> <div class="starBox"> <span style="margin:0 6px">{{v.starNum}}</span> <like-outlined /> </div> <div class="downBox"> <span style="margin:0 6px">{{v.downNum}}</span> <like-outlined :rotate='180' /> </div> </div> <p class="user"><span>{{v.username}}</span><span>{{v.createTime}}</span></p> </div>
通过reactive响应式,包裹的一层对象读取属性 xxx.data 获取数据
注意:若使用ref,子组件模板中可直接使用xxx.value;若使用reactive,包裹一层对象,读取包裹的属性