【问题标题】:can not initialize data from prop无法从 prop 初始化数据
【发布时间】:2021-04-02 13:14:59
【问题描述】:

这是我的子组件:

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

及其模板:

<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>

我在父级中使用它:

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

问题是show2数据没有定义:,这里是控制台日志:

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:

prop用于传入一个初始值;子组件 之后想将其用作本地数据属性。在这种情况下, 最好定义一个使用 prop 作为它的本地数据属性 初始值:

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

我在做同样的事情,有什么问题?

【问题讨论】:

    标签: vue.js


    【解决方案1】:

    对data属性使用箭头函数会丢失vue组件上下文,尝试使用简单函数:

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

    或者试试这个:

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2022-01-18
      • 2023-04-08
      • 2019-08-08
      • 2015-09-14
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多