programing

Vuex Store 및 계산된 속성을 사용하여 컴포넌트에 전달된 객체 배열을 루프하려면 어떻게 해야 합니까?

itsource 2022. 7. 5. 23:14
반응형

Vuex Store 및 계산된 속성을 사용하여 컴포넌트에 전달된 객체 배열을 루프하려면 어떻게 해야 합니까?

나는 Vux를 배우기 위한 프로젝트를 만들고 있다.다음과 같은 오브젝트 배열을 만들고 있습니다.

Vuex 스토어:

import Vue from "vue";
import Vuex from "vuex";

Vue.use(Vuex);

export default new Vuex.Store({
  state: {
    users: [
      { id: 1, name: 'John Doe', email: 'johndoe@gmail.com' },
      { id: 2, name: 'Jane Doe', email: 'janedoe@gmail.com'  },
      { id: 3, name: 'Mark Greywood', email: 'markgreywood@gmail.com'  },
    ]
  },
  mutations: {},
  actions: {},
  modules: {}
});

다음으로 컴포넌트 내의 에 다음과 같이 계산된 속성을 부여합니다.

컴포넌트:

<template>
  <div class="home">
    <h1>Hello from Home component</h1>

   <!-- I do not loop through the users, nothing shows --> 
    <div v-for="user in users" :key="user.id">{{ user.name }} </div>

   <!-- I get the users object in the DOM -->
    <div>{{ getUsers }}</div>
  </div>
</template>

<script>
import { mapState } from 'vuex'

export default {
  name: "Index",
  computed: mapState({
    getUsers: state => state.users
  })
};
</script>

<style scoped lang="less">

</style>

내가 뭘 잘못하고 있는지 모르겠어.

에 액세스 할 수 없습니다.users이 코드라인에서는

<div v-for="user in users" :key="user.id">{{ user.name }} </div>

컴포넌트는 다음에만 액세스 할 수 있습니다.getUsers스토어 객체에 매핑되는 (계산된 속성)users따라서 항상users스토어 상태 변경,getUser또한 갱신됩니다.따라서 컴포넌트의 계산된 속성을 반복해야 합니다.

따라서 이 반복은 다음과 같이 해야 합니다.

<div v-for="user in getUsers" :key="user.id">{{ user.name }} </div>

이것을 변경하다

    <div v-for="user in users" :key="user.id">{{ user.name }} </div>


이것을 위해서

    <div v-for="user in getUsers" :key="user.id">{{ user.name }} </div>

mapState 행에서는 컴포넌트에 대해 'Hey my store.users is in the getUsers variable' 컴포넌트는 'users'에 대해 알 수 없습니다.그런 식으로 변수를 만든 게 아니에요.

또 하나의 방법은 루프를

    <div v-for="user in $store.state.users" :key="user.id">{{ user.name }} </div>

이 경우 계산 속성 'getUsers'를 삭제할 수 있습니다.

언급URL : https://stackoverflow.com/questions/58681381/how-to-loop-through-an-array-of-objects-passed-to-a-component-with-vuex-store

반응형