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

Vue getter returns undefined when page reload

我有一个博客,里面有一些 post。当您单击预览时,您将重定向到页面 post。 在 post 的页面上,我使用 getter 来加载正确的 post (我使用 find 函数来 return 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

中调用了getter
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. return 错误,因为状态为空
2. return 正确的对象
// 下面的屏幕

所以从前面看一切正常,但在控制台和应用程序中完全不正常。
我认为正确的方法是在 created 钩子中调用 getters。我要改变什么?是计算的 prop,getters 还是 state 有问题?

POST 页数:

<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>

错误日志非常明确,在您的 Ricetta 组件模板中某处有一个 xxx.validate,但 xxx 未定义。

因此,您的应用程序崩溃并停止工作。我怀疑它与 Vuex

有什么关系

您正在尝试 validate 未定义 属性。所以你需要先检查ricetta

这样试试:

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

数据库同步是异步的,ricettario最初是一个空数组。同步完成后重新计算计算值并且 ricettario 数组被填充,组件被更新。

即使 ricettario 不为空,find 也可能 return undefined 如果找不到任何内容。这个需要在使用ricetta的地方处理:

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