Porfinogeneta
Porfinogeneta

Reputation: 49

Problem with watching prop changes Vue.js

What's the problem

I wanted to assign a local component variable to prop. I constantly get Vue alert Invalid watch handler specified by key "undefined". Maybe the case is that the prop is passed from another component, where I use v-model, but I don't really know. I would really appreciate your help, because my small exercise project really depends on this mechanic.

Parent Component

Here I have some HTML select, this is where I actually model my state.selectedPhysicsModule

<template>
  <div>
    <div>
      <h1>Some header</h1>
    </div>
    <form class="choosePhysicsModule">
      <label for="selectedPhysicsModule"></label>
      <select class="select_Module" id="selectedPhysicsModule" v-model="state.selectedPhysicsModule">
        <option :value="option.value" v-for="(option, index) in importedListToSelect" :key="index">
          {{option.name}}
        </option>
      </select>
    </form>
    <list_of_exercises  v-if="state.selectedPhysicsModule" :what_exercises="state.selectedPhysicsModule"/>
  </div>
</template>

<script>

export default {
  name: 'ChoosePhysicsModule',
  components: {list_of_exercises},
  setup() {
    const state = reactive({
      selectedPhysicsModule: null,
    })
    return {
      state,
      importedListToSelect
    }
  }
}

Child Component

</script>

export default {
    name: "list_of_exercises",
      props: {
        whatExercises: {
          type: String,
          required: true
        }
      },
      data() {
       return {
         exercises: this.what_exercises,
       }
      },
      watch: {
        whatExercises: function () {
          this.exercises = this.whatExercises
        }
       }

Upvotes: 0

Views: 4083

Answers (1)

hatef
hatef

Reputation: 6219

In the parent component where you are passing the prop you need to add a setter for the prop passed. Here is an example:

<template>
  <div id="app">
      <label>
          <input name="whatExercises" v-model="whatExercises">
      </label>

      <ListOfExercises v-if="whatExercises" :what_exercises="whatExercises" />
  </div>
</template>

<script>
export default {
    data() {
      return {
          whatExercises: null,
      }
    }
}
</script>

P.S: as a side note, I recommend using camelCase for prop names. It's more in-line with the rest of the community. If you have time feel free to check out the style guide on the official website.

Upvotes: 1

Related Questions