简体   繁体   中英

Vue - Loosing child reactivity by passing props from parent, dependent on the state

In my code I'm deleting an 'exercise' object successfully from the state, but it is not getting deleted on the component. The parent component takes in the data from the state and passes the 'exercises' array to the child where it can be deleted.

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 ''
      },
    },
  },

Inside HorizontalExercises I have a function that successfully deletes the exercise from state, but I can't get it to dissapear from the component prop so it doesn't renders. It only dissapears when I re-render the RoutinePanel component.

The state looks something like this:

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

Here`s the mutation used:

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)
},

i'm thinking on just making everything dependant from the state and not passing props may work.

Sorry maybe a bit confusing it`s my first question.

I think maybe you are trying to pass values from the state :selected-routine="selectedRoutine" if your variable is passed from this.$store.state.selectedRoutines it might not work (it was not reactive for me).

If so then try using the getters instead. https://vuex.vuejs.org/guide/getters.html

You can map them in your data and pass them down as props, it's reactive in my project. And then you can map your getters in your computed properties. https://vuex.vuejs.org/guide/getters.html#the-mapgetters-helper

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM