Vue-根据状态,通过从父对象传递道具来释放子对象的反应性



在我的代码中,我成功地从状态中删除了一个"exercise"对象,但它没有在组件上被删除。父组件接收状态中的数据,并将"练习"数组传递给子组件,在子组件中可以删除该数组。

Index passes the exercises as selectedRoutine to RoutinePanel
<v-row v-else justify="center">
<v-col cols="12" sm="9" md="7" class="text-center">
<RoutinePanel
:selected-day="selectedDay"
:selected-routine="selectedRoutine"
/>
</v-col>
</v-row>
Then RoutinePanel passe each exercise as a prop to HorizontalExercises
<div v-for="exercise in selectedRoutine" :key="exercise.name">
<HorizontalExercises :exercise="exercise" :selected-day="selectedDay" />
</div>
HorizontalExercises
export default {
props: {
exercise: {
type: Object,
default: () => {
return {
name: 'Exercise',
sets: 0,
reps: 0,
weight: 0,
id: 0,
}
},
},
selectedDay: {
type: String,
default: () => {
return ''
},
},
},

在HorizontalExercise中,我有一个函数可以成功地将练习从状态中删除,但我无法将其从组件道具中删除,因此它不会渲染。只有当我重新呈现RoutinePanel组件时,它才会消失。

状态看起来像这样:

routines: [
{
day: 'monday',
exercises: [
{
name: 'bicycle',
duration: '5 min',
id: 0,
},
]

这是使用的突变:

deleteExercise(state, payload) {
const routineIndex = state.routines.findIndex(
(routine) => routine.day === payload.day
)
const exerciseIndex = state.routines[routineIndex].exercises.findIndex(
(exercise) => exercise.id === payload.id
)
state.routines[routineIndex].exercises.splice(exerciseIndex, 1)
},

我正在考虑让一切都依赖于国家,而不传递道具可能会奏效。

抱歉,也许有点困惑——这是我的第一个问题。

我认为您可能正在尝试从状态传递值:selected-routine="selectedRoutine"如果您的变量是从this.$store.state.selectedRoutines传递的,它可能不起作用(对我来说不是反应性的(。

如果是,请尝试使用getters。https://vuex.vuejs.org/guide/getters.html

你可以将它们映射到你的数据中,并将它们作为道具传递下去,这在我的项目中是被动的。然后,您可以将getter映射到computed属性中。https://vuex.vuejs.org/guide/getters.html#the-mapgetters助手

最新更新