programing

동작의 Axios 데이터와 함께 컴포넌트에서 Vuex getter 사용

sourcetip 2022. 7. 15. 23:13
반응형

동작의 Axios 데이터와 함께 컴포넌트에서 Vuex getter 사용

get 요청을 하면 Vuex 작업 및 변환이 업데이트됩니다.단, getters와 state는 동시에 갱신되지 않습니다.두 번째 get 요청을 하면 업데이트가 됩니다.

Vuex 스토어

import api from '../../api/main'

export const table_informations = {

    state: {
        //  Tek dosya verisi get listesi
        fileName_and_sheetName:[],
        table_value :[]
    },

    getters: {
        Gtable_Value(state){
            return state.table_value
        },
    },

    mutations: {
        Mtable_Value(state,data){
            state.table_value = data
        },
    },

    actions: {
        table_value({commit}){
            api.allshowdata().then(res => res.data).then(items => {
                return commit('Mtable_Value',items)
            })
        },
    },
}

마이테이블표시하다

<template>
  <div>
    <b-button @click="this.run"></b-button>
  </div>
</template>
<script>
import {table_informations} from "../../../store/file_informations/table_informations";
export default {
  name: "table",
  methods:{
    run(){
      this.$store.dispatch('table_value')
      let data =this.$store.getters.Gtable_Value
      console.log(data)
    }
  },
}
</script>

버튼을 누르면 액션과 변환은 최신 데이터를 가지고 있지만 상태 및 수신자는 최신 데이터를 가지고 있지 않습니다.두 번째 요청 시 최신 데이터가 포함되어 있습니다.내 액션, 변환 또는 요청 취득에는 문제가 없습니다.제 Vuex 스토어 빼고는 다 괜찮아요.

변수를 getter 값으로 설정하기 전에 비동기 요청이 완료될 때까지 기다리지 않습니다.약속이 해결될 때까지 기다려야 하지만, getter에는 computed를 사용하는 것이 좋습니다.이 패턴은 getter가 로드된 후 다른 작업을 수행할 필요가 없는 경우에 적합합니다.

import { mapGetters } from 'vuex';  // mapGetters
import {table_informations} from "../../../store/file_informations/table_informations";
export default {
  name: "table",
  computed: {
    ...mapGetters(['Gtable_Value']) // Create computed that syncs with Vuex getter
  },
  methods: {
    run() {
      this.$store.dispatch('table_value')
    }
  },
}

또는 계획대로 하려면 액션에서http 약속을 반환하고 메서드로 대기합니다.

가게

actions: {
 table_value({commit}){
    // return the http promise
    return api.allshowdata().then(res => res.data).then(items => {
      return commit('Mtable_Value',items)
    })
  },
},

마이테이블표시하다

import {table_informations} from "../../../store/file_informations/table_informations";
export default {
  name: "table",
  methods: {
    async run() {                                   // async keyword
      await this.$store.dispatch('table_value')     // awaiting the promise
      let data = this.$store.getters.Gtable_Value
      console.log(data)
    }
  },
}

언급URL : https://stackoverflow.com/questions/66308289/use-vuex-getter-in-component-with-actions-axios-data

반응형