programing

액션을 호출하는 방법(NuxtJs

javaba 2022. 8. 27. 22:08
반응형

액션을 호출하는 방법(NuxtJs

제 가게에서 제 vue를 호출하려고 합니다.

다음은 제 스토어에 있는 파일 alimens.js입니다.

import Vue from 'vue';
import Vuex from 'vuex';
import axios from 'axios';

Vue.use(Vuex, axios);

export const state = () => ({
  aliments: {},
})
export const mutations = () => ({
  SET_ALIMENTS(state, aliments) {
    state.aliments = aliments
  }
})
export const actions = () => ({
  async getListAliments(commit) {
    await Vue.axios.get(`http://localhost:3080/aliments`).then((response) => {
      console.log(response);
      commit('SET_ALIMENTS', response);
    }).catch(error => {
      throw new Error(`${error}`);
    })
    // const data = await this.$axios.get(`http://localhost:3080/aliments`)
    // commit('setUser', user)
    // state.user = data;
    // return state.user;
  }

})
export const getters = () => ({
  aliments (state) {
    return state.aliments
  }
})

vue에서 다음과 같이 알리미션 목록을 재생합니다.

{{ this.$store.state.aliments }}

나는 나의 행동을 다음과 같이 부른다.

<script>
import { mapGetters, mapActions } from 'vuex'

export default {

  computed: {
    ...mapGetters(['loggedInUser', 'aliments']),
    ...mapActions(['getListAliments']),
    getListAliments() {
      return this.$state.aliments
    }
  }
}
</script>

제 실수가 어디에 있는지 모르겠어요:/

NB: 디스패치('aliments/getListAliments') 버튼 클릭 방식으로도 시도했습니다.근데 안 되네...

문제는 컴포넌트의 "계산" 섹션에 액션을 매핑하고 있다는 것입니다.이 경우 "방법" 섹션에 매핑해야 합니다.

Stack Overflow에 오신 것을 환영합니다.

질문에 신속하게 답변하기 위해 다음과 같은 조치를 취할 수 있습니다.

this.$store.dispatch('<NAME_OF_ACTION>', payload)

또는 a를 통해서도mapActions~하듯이

...mapActions(['getListAliments']), // and you call `this.getListAliments(payload)`

혹은 아직

...mapActions({
  the_name_you_prefer: 'getListAliments' // and you call `this.the_name_you_prefer(payload)`
}), 

getter의 경우 이미 2개의 정의가 있기 때문에 동일한 프로세스입니다.['loggedInUser', 'aliments']계산된 값인 것처럼 게터에게 전화를 걸기만 하면 됩니다.<pre>{{ aliments }}</pre>

또는 조금 더 해야 할 때(필터링 등)

getListAliments() {
    return this.$store.getters['aliments']
}

그러나 귀사의 스토어는 우리가 말하는 One-to-Rule-the-all입니다. Nuxt를 사용하고 있기 때문에 모듈 스토어를 매우 쉽게 활용할 수 있습니다.

어플리케이션이 커짐에 따라 모든 것을 하나의 스토어 파일에 저장하기 시작합니다.~/store/index.js파일)에 기입한 것이 아니라, 다른 스토어를 간단하게 작성할 수 있습니다.index.js예를 들면, 라고 하는 파일이 있으면, 보다 간단하게 할 수 있습니다.

~/store/food.js와 함께

import axios from 'axios'

export const state = () => ({
    aliments: {},
})

export const getters = {
    aliments (state) {
        return state.aliments
    }
}

export const mutations = {
    SET_ALIMENTS(state, aliments) {
        state.aliments = aliments
    }
}

export const actions = {
    async getListAliments(commit) {
        await axios.get('http://localhost:3080/aliments')
            .then((response) => {
                console.log(response);
                commit('SET_ALIMENTS', response.data);
            }).catch(error => {
                throw new Error(`${error}`);
            })
  }
}

참고로 Nuxt를 사용하는 경우 이 라인은

axios.get('http://localhost:3080/aliments')...

간단히 말하면

axios.get('/aliments')...

이 스토어에 전화를 걸려면 다음과 같은 파일 이름 접두사만 붙이면 됩니다.

...mapActions(['food/getListAliments'])
// or
...mapActions({ getListAliments: 'food/getListAliments' })
// or
this.$store.commit('food/getListAliments', payload)

이 과정에서 도움이 될 수 있는 또 다른 이름:

  • 당신의 행동에 따라getListAliments서버로부터 데이터를 취득하고 있는 경우, 그 이름을fetchAliments

  • 흥분하여aliments당신은 실제로 목록을 돌려주고 있어요, 전 이름을 붙이고 싶어요.getAllAliments

Nuxt는 훌륭하고, Disconsum에 관한 커뮤니티도 넓어졌습니다.o)


편집

또한 을 기억한다actions에 설정되어 있다.methods

다음 작업을 수행할 수 있습니다.

...
export default {
    methods: {
        ...mapActions(['getListAliments]),
    },
    created() {
        this.getListAliments()
    }
}

스토어 액션에서는 반드시 다음 내용을 기입해 주십시오.

async getListAliments({ commit }) { ... }

통과된 속성을 분해하는 것이기 때문에 곱슬곱슬한 괄호로 묶습니다.

async getListAliments(context) { 
   ...
   context.commit(...)
}

언급URL : https://stackoverflow.com/questions/60490156/how-to-call-an-action-nuxtjs

반응형