页面重新加载时Vue getter返回未定义

我有一个博客,里面有一些帖子。当您单击预览时,您将重定向到页面帖子。在帖子的页面上,我使用 getter 加载正确的帖子(我使用find函数返回object.name对应于对象数组中的正确对象)。


const state = {

    ricettario: [], // data that contains all recipes (array of objects)

}


const actions = {

    // Bind State and Firestore collection

    init: firestoreAction(({ bindFirestoreRef }) => {

        bindFirestoreRef('ricettario', db.collection('____').orderBy('data'))

    })


const getters = {

    caricaRicetta(state) {

        console.log('Vuex Getter FIRED => ', state.ricettario)

        return nameParamByComponent => state.ricettario.find(ricetta => {

            return ricetta.name === nameParamByComponent

        })

    }

}

在组件中,我在computed property


computed: {

    ...mapGetters('ricettaStore', ['caricaRicetta']),

    ricetta() {

      return this.caricaRicetta(this.slug) // this.slug is the prop of the URL (by Router)

    }

  }

一切都以正确的方式进行,但是当我在 POST PAGE 中重新加载页面时,getter 将触发 2 次:

1. 因为状态为空而返回错误

2. 返回正确的对象

// 下面的屏幕

http://img3.mukewang.com/62aadc7d0001ffba06760443.jpg

因此,从正面看一切正常,但在控制台和应用程序中却完全不行。

我认为正确的方法是在created钩子中调用 getter。我要改变什么?计算的道具、吸气剂或状态有问题吗?


发布页面:


<template>

  <div v-if="ricetta.validate === true" id="sezione-ricetta">

    <div class="container">

      <div class="row">

        <div class="col s12 m10 offset-m1 l8 offset-l2">

          <img

            class="img-fluid"

            :src="ricetta.img"

            :alt="'Ricetta ' + ricetta.titolo"

            :title="ricetta.titolo"

          />

        </div>

      </div>

    </div>

  </div>

  <div v-else>

      ...

  </div>

</template>



catspeake
浏览 169回答 3
3回答

撒科打诨

您正在尝试validate未定义的属性。所以你需要先检查ricetta。试试这样:<div&nbsp;v-if="ricetta&nbsp;&&&nbsp;ricetta.validate&nbsp;===&nbsp;true"&nbsp;id="sezione-ricetta">

森栏

数据库同步是异步的,ricettario最初是一个空数组。ricettario一旦同步完成并填充数组,将重新计算计算值,更新组件。即使ricettario不是空的,如果它什么也没找到,find可能会返回undefined。这需要在使用的地方处理ricetta:<div&nbsp;v-if="ricetta&nbsp;&&&nbsp;ricetta.validate"&nbsp;id="sezione-ricetta">

PIPIONE

错误日志非常明确,xxx.validate您的组件模板中有一个地方Ricetta,但xxx未定义。因此,您的应用程序崩溃并停止工作。我怀疑它与 Vuex 有什么关系
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

JavaScript