Programing

vuex에서 커밋을 사용하는 가장 좋은 방법은 무엇인가?

c10106 2022. 3. 16. 21:42
반응형

vuex에서 커밋을 사용하는 가장 좋은 방법은 무엇인가?

나는 프로젝트를 만들기 위해 매일 vue와 vuex를 사용하며, 때때로 http 요청을 할 때 주에 돌연변이를 만들 필요가 없다.나는 다음과 같은 방법을 사용한다.

actions:{
   theAction({},payload){
      // bla bla
   }
}

이렇게 하면 나는 경고를 받을 수 있지만, 나는 그 행동을 할 수 있다.나는 이 경고를 피하기 위해 관찰할 수 있었다. 어떤 사람들은 구성 요소 안에서 이 행동을 만들 것을 권고한다. 왜냐하면 이상적인 것은 국가의 논리를 다루는 것이기 때문에 지루하기 때문이다.

내 질문은, 이런 종류의 행동을 만드는 가장 좋은 방법은 무엇일까?

이 수신된 데이터를 많은 구성요소에 사용할 경우 돌연변이를 사용하여 상태로 저장하십시오.특정 구성 요소에서 데이터를 사용하지만 구성 요소에서 직접 수신하지 않으려는 경우 이러한 모든 요청이 배치된 api 폴더의 어딘가에 이 호출을 spareete js-module에 넣을 수 있다.

업데이트:

api 폴더의 js-module 예: 항목.js

import axios from 'axios'

export default {
  async getItems (options) {
    const { data: result } = await axios.post('/api/items', options)
    return result
  }
}

사용법: MyComponent.부에를 하다

import itemsApi from '@/api/items'
...
export default {
...
data () {
  return {
    items: []
  }
},
methods: {
   async loadItems() {
      this.items = await itemsApi.getItems({})
  }
}

이 API를 여러 구성 요소에서 사용하려면 이 loadItems 함수를 사용하여 mixin을 생성하십시오.

이것은 주 모듈 항목의 작용과 돌연변이의 예다.js:

import itemsApi from '@/api/items'

const GET_ITEMS = 'GET_ITEMS'

const state = {
  items: []
}

const actions = {
  async getItems ({ commit }, params) {
    const items = await itemsApi.getItems(params)
    commit(GET_ITEMS, items)
  },
}
const mutations = {
  [GET_ITEMS] (state, items) {
    state.items = items
  }
}
export default {
  namespaced: true,
  state,
  actions,
  mutations
}

사용량:

MyComponent.부에를 하다

<script>
import { mapActions, mapState } from 'vuex'
...
export default {
...
computed: {
  ...mapState({
    items: state => state.items.items
  }),
},
methods: {
   ...mapActions({
     getItems: 'items/getItems',
    }),
   async loadItems() {
      await this.getItems({})
      // now you have the loaded items in this.items
  }
}

어쩌면 유용한 것을 덧붙일 수 있을 것이다.

NUXT와 같은 프레임워크를 사용하면 플러그인을 제공할 수 있다.따라서 저장 돌연변이와 관련이 없지만 다른 구성 요소에서 실용적인 API 호출의 경우 플러그인은 분명한 해결책이 될 것이다.

nnxt.config.js

  /*
  ** Plugins to load before mounting the App
  */
  plugins: [
    '@/plugins/register-api',
  ],

~/register/register-api.js

import Vue from 'vue';
import api from '~/api';

export default function ({ store }) {
  store.$api = api;

  const ApiUtilityPlugin = {
    install() {
      Vue.prototype.$api = api;
    },
  };

  Vue.use(ApiUtilityPlugin);
}

~/api/index.js

import { service } from 'package'

export default function () {
  return {
    async getValue() {
      await service.getValue();
    },
  };
}

Vue 구성 요소

<script>
export default {
 methods: {
  callAPI() {
   this.$api.getValue();
 },
};
</script>

따라서 이러한 방식으로 당신은 당신의 앱에서 스토어를 잘못 사용하지 않고 다른 API를 호출할 수 있다.

참조URL: https://stackoverflow.com/questions/60191701/what-is-the-best-way-to-use-commits-in-vuex

반응형