【问题标题】:Can't access getters in the store for Vue when in a template because it "is not a function"在模板中时无法访问 Vue 商店中的 getter,因为它“不是函数”
【发布时间】:2022-01-17 04:01:19
【问题描述】:

我是 vue 和 vuex 的新手,我也在使用 Nuxt。我想在我的模板中使用一个函数来搜索我从 API(在 vuex 中)获取的一些数据。我不明白为什么我总是得到

state.allHandhelds.values.findIndex is not a function

我的模板是这样的:

<div>{{ handheldID("Form Factor") }}</div>

在我的计算中,我这样调用函数:

 computed: {
    ...mapGetters(["allHandhelds"]),
    handheldID(merkmal) {
      return this.$store.getters.indexFinder(merkmal);
    },
  },

在 vuex 中,我将其定义为 getter:

export const getters = {
   indexFinder(state, merkmal) {
    return state.allHandhelds.values.findIndex(
      (el) => el === merkmal
    ); /* Index des Merkmals finden */
  },
};

知道我哪里出错了吗?

【问题讨论】:

    标签: javascript vue.js nuxt.js vuex


    【解决方案1】:

    您必须使用方法访问样式,例如:

    export const getters = {
    
     indexFinder: (state) => (merkmal) => {
          return state.allHandhelds.values.findIndex(
             (el) => el === merkmal
        ); 
      }
    };
    

    或语法:

    export const getters = {
       indexFinder(state) {
        return (merkmal)=> {
           return state.allHandhelds.values.findIndex(
          (el) => el === merkmal
        ); /* Index des Merkmals finden */
       }  
    },
    };
    

    【讨论】:

    • 那行不通。不幸的是,我仍然收到“state.allHandhelds.values.findIndex 不是函数”错误
    • 请分享您如何定义状态
    • 数据加载有问题。如果我只是从 getter 返回“return state.allHandhelds.values”,它可以工作,如果我之后附加 .findIndex 它也可以工作,但是一旦我重新加载页面,它就会再次中断。是不是因为我的商店里也有一个 fetch ,所以获取了数据? export const actions = { fetchAllHandhelds(context) { return fetch(URLisHERE) .then((response) =&gt; response.json()) .then((data) =&gt; { context.commit("setHandhelds", data); }) .catch((err) =&gt; console.error(err)); }, };
    • 我这样定义状态:export const state = () =&gt; ({ allHandhelds: [], });
    • 根据状态你应该做state.allHandhelds.findIndex(
    猜你喜欢
    • 2017-04-17
    • 1970-01-01
    • 2021-10-20
    • 2021-10-23
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-06-11
    • 1970-01-01
    相关资源
    最近更新 更多