【问题标题】:VueJS: Passing Vuex property value from parent to child component and avoid "undefined"VueJS:将 Vuex 属性值从父组件传递给子组件并避免“未定义”
【发布时间】:2018-10-23 01:56:30
【问题描述】:

我正在使用 Vuex 属性从父组件传递一个参数。但是,当组件加载完毕后,Vuex 属性仍然是undefined,产生如下错误信息:

[Vue 警告]:渲染错误:“TypeError:无法读取属性 '0' 未定义”

我正在传递这样的属性:

<card
    :image="$store.state.company.card_img[0].url"
></card>

它工作正常,但我想知道如何以正确的方式避免错误消息。

【问题讨论】:

    标签: vuex


    【解决方案1】:

    您可以使用计算属性来检查可用数据:

    computed: {
      imageUrl: function() {
        if (this.$store.state.company && this.$store.state.company.card_img && this.$store.state.company.card_img.length > 0) {
          return this.$store.state.company.card_img[0].url
        }
        return null;
      }
    }
    

    在模板中

    <card
        :image="imageUrl"
    ></card>
    

    另一种方法是使用vuex getters

    【讨论】:

    • 谢谢,但是使用此代码,我的组件不再显示,并且我收到以下错误消息: [Vue warn]: Error in render: "TypeError: Cannot read property 'card_img' of undefined "。
    • 谢谢!现在,它可以工作了 :-) 只需将 this. 添加到返回的属性中,这个答案就完美了。
    • 谢谢!更新了我的答案!
    猜你喜欢
    • 1970-01-01
    • 2017-10-17
    • 1970-01-01
    • 2020-02-04
    • 2017-01-07
    • 2020-11-23
    • 2021-12-27
    • 2021-04-22
    • 2020-09-16
    相关资源
    最近更新 更多