Vue js计算属性评估顺序

时间:2017-09-04 08:31:01

标签: vue.js vuejs2 vue-component vuex

我有一个使用'data1'道具的组件。

<template>
    <div>
        <component1 :data='data1'><component1>
    </div>
<template>

此data1是一个计算属性,需要另一个计算数据来计算其中一个值:

computed: {

    componentInfo: function() {
        return this.$store.state.componentData;
    }

    data1: function() {
        return {value1: this.componentInfo.value1, ... other values}
    }
}

我的问题是组件在从商店获取componentInfo之前尝试评估data1值(这会导致错误,因为this.componentInfo仍未定义)

如何处理这种情况?

1 个答案:

答案 0 :(得分:0)

这很容易处理。只需向计算属性添加额外的if

data1 () {
  if (this.componentInfo) { // check if it exists
    return { value1: this.componentInfo.value1, ... other values }
  } else {
    return {} // some default value
  }
}
相关问题