繁体   English   中英

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

[英]Vue getter returns undefined when page reload

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

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.返回错误因为state是null
2.返回正确的object
//下面的屏幕

在此处输入图像描述

因此,从正面看一切正常,但在控制台和应用程序中却完全不行。
我认为正确的方法是在created钩子中调用 getter。 我要改变什么? 计算的 prop、getter 或 state 有问题吗?

发布页面:

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

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

试试这样:

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

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

即使ricettario不是空的,如果它什么也没找到, find也可能返回undefined 这需要在使用ricetta的地方处理:

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

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

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM