将计算的属性作为prop传递(未定义)

时间:2020-09-30 13:14:15

标签: javascript vue.js vue-component

我有一个salePrice()计算属性,我正试图将其传递给子组件。问题在于该组件说salePrice未定义。

我需要它具有反应性,但似乎没有用。

<v-tab-item value="repairs_images" class="px-3 py-3" :eager="true">
    <h2>Repairs & Images</h2>
    <images_page v-if="realestate.id" :realestate="realestate"></images_page>
    <repairs_page v-if="realestate.id && salePrice !== undefined" :realestate="realestate" :salePrice="salePrice"/>
</v-tab-item>

这是salePrice补偿。属性:

salePrice() {
    if (this.realestate.use_manual_price === true) {
        return this.realestate.manual_price
    }
    return this.realestate.price
},

每当用户更改use_manual_price时,情况都会改变。在调试模式下,我看到它可以在应用程序中运行,但更改不会传播到子级。

您知道如何使其工作吗?我还尝试在子组件中使用this.$root.salePrice

1 个答案:

答案 0 :(得分:0)

看起来应该可以,如果您提供一个复制链接(如jsfiddle),效果会更好。

问题可能是您的计算属性实际上由于this.realestate而返回未定义的值(如果进行检查)。首先如何定义或获取此值?

无论如何,您可以尝试:

  • salePrice的prop定义赋予默认值,例如

     props:{
      salesPrice: {type: Number, default: 0}
      }
    
  • 或者还向您的计算属性添加另一个if-check,如果在实例实例的那个时刻this.realestate.price也未定义的情况下返回默认值。

    salePrice() {
    if (this.realestate.use_manual_price === true) {
        return this.realestate.manual_price
    } 
    else if(this.realestate.price){
    return this.realestate.price
    }
     return 'dummy price'
    },

据我所知,如果父组件的数据不可用,道具当然可以首先呈现为“ undefined”。而且,如果要处理计算属性,它可能会在计算属性返回值之前引发您提到的错误。

请让我知道!

相关问题