Vuejs에서 vuex Store로 데이터를 전달하는 방법
vuejs 컴포넌트와 vuex 스토어가 있습니다.
vue 컴포넌트에서 vuejs 스토어로 데이터를 보내고 vuex에서 데이터를 DB로 푸시하는 함수를 호출하고 싶습니다.
currentUser에서 데이터를 가져오지만(작동 가능), vuex 스토어에서 다음 오류가 발생합니다.Cannot read property 'push' of null
.
나는 달린다createPost
그것은 작동하지만 데이터가 vuex 스토어에 푸시되지 않는 것은 위의 오류 때문인 것 같습니다.
#vuejs component
import { mapState, mapGetters, mapMutations, mapActions } from "vuex";
import {
SET_NEWPOST,
ADD_TAGS,
SET_USERDATA,
SET_GENERAL
} from "@/store/posts/mutations";
methods: {
...mapMutations("posts", {
updateInformation: SET_NEWPOST,
setUserData: SET_USERDATA,
addGeneral: SET_GENERAL,
addTags: ADD_TAGS
}),
...mapActions("posts", {
create: "triggerAddProductAction"
}),
async createPost() {
this.updateInformation({
content: this.content,
url: this.newOne
});
this.updateUserData();
this.createOne();
}
}
vuex 스토어
...
const state = {
products: []
}
const mutations = {
[addProduct]: (state, product) => state.products.push(product)
},
const actions: {
createUserProduct: async ({ commit, rootState }, product) => {
const userProductDb = new UserProductsDB(
rootState.authentication.user.id
);
const createdProduct = await userProductDb.create(product);
commit("addProduct", createdProduct);
},
triggerAddProductAction: ({ dispatch, state, commit }) => {
const post = state.newPost;
dispatch("createUserProduct", post);
}
}
당신의 형식은 좀 이상하다고 생각합니다.가게를 이렇게 만들어 보세요.화살표 함수와 화살표 이외의 함수를 함께 사용하면 참조되는 항목에서도 부작용이 발생할 수 있습니다.
대부분 볼 수 있는 건, 제가 그 부분을 제거했다는 겁니다.const
모든 것을 오브젝트 리터럴에 직접 배치합니다.또, 이 파일도 삭제했습니다.Destructuring
의addProduct
논리적으로 보이지 않기 때문입니다.
const store = new Vuex.Store({
state: {
products: []
},
mutations: {
addProduct: (state, product) => {
state.products.push(product)
console.log('Added Product:', product)
console.log('products', state.products)
}
},
actions: {
async createUserProduct({ commit }, product) {
commit("addProduct", product);
}
}
});
new Vue({
el: "#app",
store,
mounted() {
this.$store.dispatch('createUserProduct', 1)
}
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.17/vue.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/vuex/3.1.0/vuex.min.js"></script>
<div id="app"></div>
여기서 가장 큰 문제 중 하나는 실제로 자신의 성분에 있는 돌연변이를 직접 불러온다는 것입니다.돌연변이는 항상 직접적으로가 아니라 행동으로 불러야 한다.이는 돌연변이가 동기화되고 액션이 비동기화될 수 있기 때문입니다.Vuex 문서에서:
On to Actions 상태 변환과 결합된 비동기성은 프로그램을 매우 이해하기 어렵게 만들 수 있습니다.예를 들어 상태를 변환하는 비동기 콜백을 사용하여2개의 메서드를 호출하는 경우, 그것들이 언제 호출되고 어떤 콜백이 최초로 호출되었는지 어떻게 알 수 있습니까?이것이 바로 우리가 두 개념을 분리하고자 하는 이유입니다.Vuex에서 돌연변이는 동기 트랜잭션입니다.
store.commit('increment')
// any state change that the "increment" mutation may cause
// should be done at this moment.
비동기 작업을 처리하기 위해 Actions를 소개합니다.
따라서 다음과 같은 구조를 사용해야 합니다.
export const mutations = {
ADD_EVENT(state, event) {
state.events.push(event)
},
SET_EVENTS(state, events) {
state.events = events
},
SET_EVENTS_TOTAL(state, eventsTotal) {
state.eventsTotal = eventsTotal
},
SET_EVENT(state, event) {
state.event = event
}
}
export const actions = {
createEvent({ commit, dispatch }, event) {
return EventService.postEvent(event)
.then(() => {
commit('ADD_EVENT', event)
commit('SET_EVENT', event)
const notification = {
type: 'success',
message: 'Your event has been created!'
}
dispatch('notification/add', notification, { root: true })
})
.catch(error => {
const notification = {
type: 'error',
message: 'There was a problem creating your event: ' + error.message
}
dispatch('notification/add', notification, { root: true })
throw error
})
}
vuemastery에 의한 이 비디오도 확인해 주세요.공식 vuex 문서에도 게재되어 있습니다.https://www.vuemastery.com/courses/mastering-vuex/intro-to-vuex/
언급URL : https://stackoverflow.com/questions/55938977/how-to-pass-data-from-vuejs-to-vuex-store
'programing' 카테고리의 다른 글
npm 설치 미달 의존 관계 (0) | 2022.05.31 |
---|---|
#define 디렉티브를 통해 LLVM과 해당 버전을 감지하는 방법은 무엇입니까? (0) | 2022.05.31 |
Larabel 5 - 조건부로 변수 추가 (0) | 2022.05.31 |
maven에서 Java 버전 지정 - 속성과 컴파일러 플러그인의 차이점 (0) | 2022.05.31 |
Vue js - 이미지 소스를 찾을 수 없을 때 alt 이미지 설정 (0) | 2022.05.31 |