【发布时间】:2019-09-20 04:19:51
【问题描述】:
我有一个 vuejs 组件和一个 vuex 商店。
我想将数据从 vue 组件发送到 vuejs 存储,然后在 vuex 中调用一个函数,将数据推送到数据库。
我从 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);
}
}
【问题讨论】:
-
您将数据作为第二个参数传递给
dispatch,例如传递1的值,使用:this.$store.dispatch('createUserProduct', 1) -
是的,我明白,但没有帮助我
-
const post = ..是空的,我不知道为什么 -
我认为这是因为您格式化对象的方式
-
我测试了不同的方法,但每次都出现同样的错误
标签: javascript vue.js vuejs2 vuex