user3618000
user3618000

Reputation: 65

can not initialize data from prop

here is my child component:

export default {
  name: "SnackBar",
  props: ["show", 'msg', 'progress'],
  data: () => ({
    show2: this.show,
  }),
}

and its template:

<template>
  <div class="text-center">
    <v-snackbar
      v-model="this.show2"
      :multi-line="true"
      timeout="-1"
    >
      {{ msg }}
      <template v-slot:action="{ attrs }">
        <v-progress-circular
          v-if="progress"
          style="float: right"
          indeterminate
          color="red"/>
        <v-btn
          color="red"
          text
          v-bind="attrs"
          @click="show2 = false">
          Close
        </v-btn>
      </template>
    </v-snackbar>
  </div>
</template>

and I use it in the parent :

<SnackBar :show="snackbar.show" :msg="snackbar.msg" :progress="snackbar.progress"/>

the problem is that the show2 data is not defined:, here is the console log:

Property or method "show2" is not defined on the instance but referenced during render.
Make sure that this property is reactive, either in the data option, or for class-based components, by initializing the property. 

from official docs:

The prop is used to pass in an initial value; the child component wants to use it as a local data property afterwards. In this case, it’s best to define a local data property that uses the prop as its initial value:

props: ['initialCounter'],
data: function () {
  return {
    counter: this.initialCounter
  }
}

I am doing exactly the same thing, what is the problem?

Upvotes: 0

Views: 656

Answers (1)

Boussadjra Brahim
Boussadjra Brahim

Reputation: 1

Using the arrow function for the data property loses the vue component context, try to use a simple function :

export default {
  name: "SnackBar",
  props: ["show", 'msg', 'progress'],
  data(){
    return {show2: this.show,}
  },
}

or try out this :

export default {
  name: "SnackBar",
  props: ["show", 'msg', 'progress'],
  data: (vm) => ({
    show2: vm.show,
  }),
}

Upvotes: 2

Related Questions