首页 > 解决方案 > 页面重新加载时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. 返回正确的对象
// 下面的屏幕

在此处输入图像描述

因此,从正面看一切正常,但在控制台和应用程序中却完全不行。
我认为正确的方法是在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>

标签: javascriptvue.jsvuejs2vuexgetter

解决方案


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

试试这样:

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

推荐阅读