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

英子

我有以下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`;
    }
  }
});

创建组件时,将引发错误:

TypeError: Cannot read property 'toLowerCase' of undefined
  at VueComponent.tag

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

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

BTL

默认情况下是道具,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`;
    }
  }
});

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章