最近在研究vue3,尝试写个demo练练手,但是发现传给子组件的值并没有动态更新,因为hook里面只return初始化的那一次,应该要怎么写呢?
父组件:
const props = defineProps({
user: {
type: String,
default: '',
}
})
const { user } = toRefs(props)
const { repositories } = useUserRepositories(user)
<template>
<RepositoriesList :list="repositories" />
</template>
子组件:
const props = defineProps({
list: {
type: Array,
default: []
}
})
const dataList = computed(() => props.list)
<template>
<div class="list-wrap">
<div class="has-data" v-if="dataList && dataList.length > 0">
<div class="item" v-for="item of dataList" :key="item.id">
<span>{{ item.owner.login }}</span>
<span>{{ item.name }}</span>
</div>
</div>
<div v-else class="blank">无数据</div>
</div>
</template>
hook:
export default function useUserRepositories(user) {
let repositories = reactive([]);
const getUserRepositories = async () => {
repositories = await fetchUserRepositories(user.value);
};
watch(user, getUserRepositories);
onMounted(getUserRepositories);
return {
repositories,
};
}
reactive 是返回了 proxy
它是响应式的集合。修改数据需要 obj.xxx = newXXX
reactive 主要用于对象
https://v3.cn.vuejs.org/api/b...
ref 主要用于原始类型