我在使用 Vue 3 时遇到问题。当我使用子组件并且用于生成内容的数据更新时,子组件不会进行反应式更新。我在子组件中使用
setup()
函数,我的理解是 Vue 3 中的 props 是响应式的,所以我不知道哪里出错了。
这是我的父组件:
<q-markup-table :v-show="!isLoading">
<thead>
<tr>
<th>Name</th>
</tr>
</thead>
<tbody>
<tr v-for="(detailedPerson, index) in people" :key="index">
<td>
<PersonLink :person="buildPerson(detailedPerson)"></PersonLink>
</td>
</tr>
</tbody>
</q-markup-table>
使用以下方法:
data() {
return {
people: {} as DetailedPerson[],
};
},
methods: {
buildPerson(detailedPerson: DetailedPerson): Person {
return {
slug: person.slug,
firstName: person.firstName,
lastName: person.lastName,
};
},
}
人员列表更新时,
PersonLink
不更新;它的表现就好像道具没有反应一样。这是PersonLink
代码:
<template>
<router-link :to="url">{{ name }}</router-link>
</template>
<script lang="ts">
import { defineComponent } from 'vue';
import { NameFormatter } from 'src/common/formatters';
import { Person } from './person.models';
export default defineComponent({
props: {
person: {
required: true,
type: Object as () => Person,
},
},
setup(props) {
return {
url: `/person/${props.person.slug}`,
name: NameFormatter.formatInverseName(props.person),
};
},
});
</script>
当子组件 props 在父组件级别更新时,需要做什么来确保反应性?
这些道具是反应性的,但您可以从中构造静态值,因此这些值不会更新。
您必须使用计算的引用来创建
url
和name
,如下所示:
import { defineComponent, computed } from 'vue';
setup(props) {
const url = computed(() => `/person/${props.person.slug}`);
const name = computed(() => NameFormatter.formatInverseName(props.person));
return {
url,
name,
};
}