Vuex 스토어의 돌연변이 중 하나에서 커밋을 호출할 수 있습니까?
다음과 같은 vuex 스토어가 있습니다.
import spreeApi from '../../gateways/spree-api'
// initial state
const state = {
products: [],
categories: []
}
// mutations
const mutations = {
SET_PRODUCTS: (state, response) => {
state.products = response.data.products
commit('SET_CATEGORIES')
},
SET_CATEGORIES: (state) => {
state.categories = state.products.map(function(product) { return product.category})
}
}
const actions = {
FETCH_PRODUCTS: (state, filters) => {
return spreeApi.get('products').then(response => state.commit('SET_PRODUCTS', response))
}
}
export default {
state,
mutations,
actions
}
합니다.SET_CATEGORIES
으로부터: 「변환SET_PRODUCTS
에러가
projectFilter.js:22 Uncapted (in promise) ReferenceError: commit이 정의되지 않았습니다(...)
바른른 ?법 ?? ????는 는 i i는노노 i i i i i.store.commit
★★★★★★★★★★★★★★★★★」this.commit
그러나, 이것들도 같은 에러를 나타내고 있습니다.
꼭 두 가지 돌연변이를 해야 한다면 왜 행동에서 하지 않는 거죠?작업은 비동기 작업을 수행할 필요가 없습니다.다음과 같이 commit 메서드를 액션으로 디스트럭처 할 수 있습니다.
commitTwoThings: ({commit}, payload) => {
commit('MUTATION_1', payload.thing)
commit('MUTATION_2', payload.otherThing)
}
기록을 위해.돌연변이 메서드에서 다른 돌연변이를 호출하려면 다음과 같이 수행합니다.
const mutations = {
mutationOne(state, payload){
this.commit("mutationTwo", payload)
},
mutationTwo(state, payload){
console.log("called from another mutation", payload)
}
}
는, 「변환」의 .commit
른른른변환은 상태를 변경하는 동기 호출입니다.하나의 돌연변이 내에서 다른 돌연변이를 저지르지 못하게 됩니다.
다음은 Vuex API 레퍼런스입니다.https://vuex.vuejs.org/en/api.html
핸들러는 수신하는 은 '하다'state
★★★★★★★★★★★★★★★★★」payload
더 이상은 아니다.그이상도 이하도 아니다.그러므로 너는따라서당신은고 있commit
~하듯이로undefined
..
위의 경우 단일 커밋으로 동일한 변환 핸들러의 일부로 PRODUCT 및 CATGUES를 설정할 수 있습니다.다음의 코드가 기능하는지를 시험할 수 있습니다.
// mutations
const mutations = {
SET_PRODUCTS_AND_CATEGORIES: (state, response) => {
state.products = response.data.products
state.categories = state.products.map(function(product) { return product.category})
},
// ...
}
편집: Daniel S가 제공한 아래의 답변을 참조하십시오. 디보어올바른 방법은 그의 답변에 설명된 대로 한 번의 동작에서 두 개의 돌연변이를 커밋하는 것입니다.
돌연변이 사이에 코드를 공유하려면, 당신은 당신이 나오고, 재사용할 수 있는 일과를 수행한다 새로운 기능을 만들어야 한다.돌연변이 간에 코드를 공유하려면 작업을 수행하는 새로운 기능을 만들어야 합니다. 이 기능을 다시 사용할 수 있습니다.다행히도, 돌연변이 단지 오래 된 기능, 그리고 우리는 다행히 돌연변이는기능일 뿐인데 오래된 그냥 통과할 수 있는이다.state
매개 변수 하지만 우리가 좋아하는 근처에서 이것은 꽤 쉽습니다.원하는 대로 파라미터를 설정할 수 있기 때문에 이 작업은 매우 간단합니다.
예를 들어 다음과 같습니다.
const mutations = {
SET_PRODUCTS: (state, response) => {
state.products = response.data.products
setCategories(state)
},
SET_CATEGORIES: (state) => {
setCategories(state)
}
}
function setCategories(state) {
state.categories = state.products.map(product => product.category)
}
여러 돌연변이 사이의 상태에 영향을 미치는 공통 코드가 있다면 모든 돌연변이에 동일한 코드를 복제해야 하나요?아니면 더 좋은 방법이 있을까요?
액션에 관한 Vuex 문서를 읽어보면 그 용도가 매우 명확합니다.
- 상태를 변이시키는 것이 아니라 돌연변이를 저지르다
- 임의의 비동기 조작을 포함할 수 있습니다.
동작에는 비동기 코드를 포함할 수 없습니다.실제로 다음 예는 정확합니다.
increment (context) {
context.commit('increment')
}
복수의 돌연변이를 실행하기 위한 조작의 사용에는 문제가 없습니다.
이 경우 SET_PRODUCTS라는 하나의 변환만을 고려해야 합니다.
// mutations
const mutations = {
SET_PRODUCTS: (state, response) => {
state.products = response.data.products
state.categories = state.products.map(function(product) { return product.category})
}
}
SET_CATORGIES를 개별적으로 호출할 필요는 없습니다.생각해 봐!카테고리는 제품이 변경된 경우에만 변환될 수 있습니다.또한 SET_PRODUCTS를 통해서만 제품을 변경할 수 있습니다.
편집 : 비슷한 문제를 우연히 발견했는데 해결 방법은 vuex getter를 사용하는 것이었습니다.https://vuex.vuejs.org/en/getters.html
카테고리는 실제로 제품의 "계산된" 버전입니다.카테고리를 getter로 지정하면 제품과의 동기화를 유지할 수 있어 저장소의 데이터 중복을 방지할 수 있습니다.
제목에 있는 질문에 답하기 위해 원래의 답변을 남깁니다.
Daniel Buckmaster 솔루션의 대안:
const mutations = {
SET_PRODUCTS: (state, response) => {
state.products = response.data.products
this.SET_CATEGORIES(state)
},
SET_CATEGORIES: (state) => {
state.categories = state.products.map(product => product.category)
}
}
보시다시피 돌연변이 자체를 직접 호출할 수 있습니다.(Daniel이 말했듯이, 결국 그것들은 단순한 기능일 뿐입니다.)
나는 이것이 원래의 질문에 대한 더 적절한 대답이라고 믿는다: 코드 복제나 추가 기능 없이 돌연변이를 구성하는 실제 방법이다.
먼저 Vue 버튼을 변수에 할당합니다.main.js:
export const app = new Vue({
router,
vuetify,
store,....
그런 다음 "app" 변수를 변환을 정의하는 js 파일로 가져옵니다.modules.js의 경우:
import { app } from "../../main";
이제 "앱"으로 사용할 수 있습니다.$store.commit":
mutations: {
[AUTH_SET_TOKEN]: () => {
app.$store.commit(USER_SUCCESS, params );
},...
나는으로 부르기를 선호한다mutations.SET_CATEGORIES(state)
대신: - 인위적인 동작과 다른2개의 커밋을 호출하거나 실행한다.commit()
돌연변이를 안으로 단위 시험 더 어렵게 만든다.
const mutations = {
SET_PRODUCTS: (state, response) => {
state.products = response.data.products
mutations.SET_CATEGORIES(state)
},
SET_CATEGORIES: (state) => {
state.categories = state.products.map(product => product.category)
}
}
내 의견은 당신을 볼 필요가 없다는 거예요.SET_CATEGORIES
그 VueToolbox에.그 시간 여행 어떻게든지 일해야 한다.제가 틀렸다면 정정해 주세요.
생각합니다
상태 및 컴포넌트를 디버깅하기 어렵기 때문에 다른 변환에서 변환을 호출하는 것은 좋지 않은 생각이다.
const mutations = {
mutationOne(state, payload){
this.commit("mutationTwo", payload)
},
mutationTwo(state, payload){
console.log("called from another mutation", payload)
}
}
그러나 당신은 간단한 기능을 쓸 수 있고 기능은 재사용할 수 있다.
function mysecondfn(state,payload){
{
// do your stuff here
}
const mutations = {
mutationOne(state, payload){
mysecondfn(state,payload)
},
}
또 다른 솔루션을 제안합니다.
this._mutations.mutationFunction[0]()
import spreeApi from '../../gateways/spree-api'
// initial state
const state = {
products: [],
categories: []
}
// mutations
const mutations = {
SET_PRODUCTS: (state, {response,commit}) => { // here you destructure the object passed to the mutation to get the response and also the commit function
state.products = response.data.products
commit('SET_CATEGORIES') // now the commit function is available
},
SET_CATEGORIES: (state) => {
state.categories = state.products.map(function(product) { return product.category})
}
}
const actions = {
FETCH_PRODUCTS: ({commit}, filters) => { // here you destructure the state to get the commit function
return spreeApi.get('products').then(response => commit('SET_PRODUCTS', {response,commit})) // here you pass the commit function through an object to 'SET_PRODUCTS' mutation
}
}
export default {
state,
mutations,
actions
}
이걸로 고칠 수 있을 거야커밋을 액션에서 변환에 삽입하여 변환에서 커밋할 수 있습니다.도움이 되었으면 좋겠다
모든 vuex에 액세스할 수 있습니다.
this.app.store.commit("toast/show", {
mssg:this.app.i18n.t('order.ordersummary.notifymessage'),
type: "danger",
});
vuex로 i18n달러 액세스
this.app.i18n.t('order.ordersummary.notifymessage')
이것을 사용하다
const mutations = {
SET_PRODUCTS: (state, response) => {
state.products = response.data.products
this.commit('SET_CATEGORIES')
},
SET_CATEGORIES: (state) => {
setCategories(state)
}
}
언급URL : https://stackoverflow.com/questions/40487627/can-i-call-commit-from-one-of-mutations-in-vuex-store
'programing' 카테고리의 다른 글
버튼이나 링크 없이 페이지 로드 시 Bootstrap-vue 모드를 트리거하려면 어떻게 해야 합니까? (0) | 2022.07.20 |
---|---|
assert()에 대한 콜을 완전히 디세블로 하려면 어떻게 해야 합니까? (0) | 2022.07.20 |
유틸리티 클래스 설정 및 vue 구성 요소 내에서 사용 (0) | 2022.07.20 |
엄격한 에일리어스 규칙이 뭐죠? (0) | 2022.07.20 |
VueJ: 여러 컴포넌트의 Vuex getter가 작동하지 않는 것을 감시한다. (0) | 2022.07.20 |