创建的钩子中的Vue返回getter

问题描述 投票:0回答:3

我有一个博客,上面有一些帖子。当您单击预览时,您将在页面文章上重定向。在帖子的页面上,我使用吸气剂加载正确的帖子(我使用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.返回正确的对象//下面的屏幕

enter image description here

所以一切都从正面很好,但在控制台和App中根本无法正常工作。我认为正确的方法是在created挂钩中调用吸气剂。我要改变什么?计算的道具,吸气剂或状态有问题吗?

POST PAGE:

<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>
javascript vue.js vuejs2 vuex getter
3个回答
1
投票

您正在尝试validate未定义的属性。因此,您需要首先检查ricetta

尝试这样:

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

0
投票

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

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


0
投票

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

即使ricettario不为空,如果find没有发现任何内容,也可能返回undefined。需要在使用ricetta的情况下处理:

<div v-if="ricetta && ricetta.validate" id="sezione-ricetta">
© www.soinside.com 2019 - 2024. All rights reserved.