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