Vue.js道具总是未定义的,显示在Vue devtools

时间:2018-04-23 10:08:31

标签: vue.js vue-component

我有一个如下所示的图像组件:

<template>
    <div :class="wrapperClasses" class="v-image">
        <div class="holder">
            <img :src="imgUrl" alt="" :class="imgClasses">
        </div>
    </div> 
</template>

<script>
export default {
  props: {
    image: {
      type: Object,
      required: true
    },
    divClasses: {
      default: ""
    },
    imgClasses: {
      default: ""
    }
  },
  computed: {
    wrapperClasses() {
      let c = [this.divClasses];
      c.push("aspect-ratio-goes-here");
      return c.join(" ");
    },
    imgUrl() {
      if (this.image) {
        return image.url;
      }
      return "http://via.placeholder.com/600x800?text=Image+coming+soon";
    }
  }
};
</script>

然后我就这样使用它:

<v-image 
   :image='{
    "id":1,
    "model_id":1,
    "collection_name":"photos",
    "name":"medialibrary073ZM0",
    "file_name":"medialibrary073zm0.jpg",
    "mime_type":"image\/jpeg",
    "disk":"public",
    "size":53946,
    "manipulations":[],
    "custom_properties":{"primaryColor":"red"},
    "responsive_images":[],
    "order_column":1,
    "created_at":"2018-04-18 10:48:11",
    "updated_at":"2018-04-18 10:48:11",
    "url":"\/storage\/1\/medialibrary073zm0.jpg"
  }'>
</v-image>

所以一切看起来都不错。但在我的控制台中,我收到以下错误:

[Vue warn]: Error in render: "ReferenceError: image is not defined"

found in

---> <VImage> at resources/assets/js/components/VImage.vue
       <Root>

如果我看一下我的vue dev工具,我会得到以下结果:

Dev tools shows prop is correctly found

发生了什么事?为什么没有定义道具?

演示

https://codesandbox.io/s/j2v7zkn203

1 个答案:

答案 0 :(得分:1)

这只是一个简单的错误。

imgUrl() {
  if (this.image) {
    return image.url;
  }
  return "http://via.placeholder.com/600x800?text=Image+coming+soon";
}

应该是

imgUrl() {
  if (this.image) {
    return this.image.url;
  }
  return "http://via.placeholder.com/600x800?text=Image+coming+soon";
}

错过了this

另外,对于vue的东西,当你遇到行错误时调试会更容易:)

https://codesandbox.io/s/vue