Vue prop 在对计算函数的初始调用中未定义

eik*_*iko 5 javascript vue.js

我有以下 Vue 组件:

Vue.component('result', {
  props: ['stuff'],
  data: () => ({}),
  template: "<img :src='tag' class='result'></img>",
  computed: {
    tag: function tag() {
      return `pages/search/img/${this.stuff.type.toLowerCase()}_tag.png`;
    }
  }
});
Run Code Online (Sandbox Code Playgroud)

创建组件时,会抛出错误:

TypeError: Cannot read property 'toLowerCase' of undefined
  at VueComponent.tag
Run Code Online (Sandbox Code Playgroud)

但是,当我删除对 的调用时toLowerCase(),该方法会正确执行,生成具有预期类型的​​字符串。我可以通过将文件名更改为大写字母来解决这个问题,但我更愿意理解为什么 Vue 会这样。为什么只有在调用属性的方法时属性才会未定义?

更新:经过一些故障排除后,我发现this.stuff.type第一次tag()计算时未定义。调用toLowerCase()只会强制一个原本无声的错误发生错误。第一次调用函数props时未定义是否有原因?computed我应该以不同的方式编写我的组件吗?

BTL*_*BTL 0

道具是默认的null,但你可以给它们一个默认值来解决这个问题。

例子 :

Vue.component('result', {
  props: {
    stuff: {
      type: Object,
      default: {
        type: ''
      }
    }
  },
  data: () => ({}),
  template: "<img :src='tag' class='result'></img>",
  computed: {
    tag: function tag() {
      return `pages/search/img/${this.stuff.type.toLowerCase()}_tag.png`;
    }
  }
});
Run Code Online (Sandbox Code Playgroud)