【问题标题】:How to store data in Vues store如何在 Vuex 存储中存储数据
【发布时间】:2022-01-09 17:03:26
【问题描述】:

我想将购物车存储在 Vuex 商店中,我在我的 Index 组件中这样做:

storeCart: function (cookieValue) {
    apiHelper.getRequest(
        `/carts/${cookieValue}`,
        (response) => {
            this.$store.dispatch('storeCart', {
                cart: response.data,
            })
        }
    )
},

所以在mounted() 我正在检查是否有cookie,调用购物车,这样,即使我刷新页面,我也不使用购物车项目:

mounted() {
    this.cartCookie = cookieHelper.getCookie(this.cartCookieName);
    this.cartCookieValue = cookieHelper.getCookieValue(this.cartCookie);
    if(this.cartCookie) {
        this.storeCart(this.cartCookieValue);
    }
},

但问题是,刷新页面后,我无法从购物车中添加、删除或更新产品。

我的行动:

export const storeCart = ({commit}, {cart}) => {
    commit('STORE_CART', {cart});
}

还有我的突变:

export const STORE_CART = (state, {cart}) => {
    state.cart = cart;
}

那么我存储数据的方式有什么问题?

【问题讨论】:

  • “但问题是,刷新页面后,我无法添加、删除或更新购物车中的产品”——不知道为什么会这样。请提供stackoverflow.com/help/mcve
  • “我无法从购物车中添加、删除或更新产品。”你有这些动作的功能吗?
  • 而且在 storeCart 函数中,你可以立即使用突变,为什么要为此使用另一个动作?您可以将 storeCart 转移到正在运行的商店

标签: vue.js vuejs2 vue-component vuex vuex-modules


【解决方案1】:

当你刷新时,你会重置一切。

我不明白您是从 API 或购物车中提取产品吗?

无论如何尝试添加 created() 钩子并在那里调度一个或多个动作

created(){
  store.dispatch('storeCart')
}

在脚本标签顶部也添加 import for store

import store from '../store'

然后在 storeCart 操作中(您将需要某种 if 语句作为示例:

if(payload)){
call API, mutation set cookies
}else{
mutation set cookies
}

添加突变store.commit('setCookies')。 在那个突变中,只需获取您之前保存的 cookie 并将它们保存到

store:{
cartCookie:{}, 
cartCookieValue:{}
}

为这两个创建 getter 并在 computed:{} props 中调用它们(下面有购物车 getter 示例)。

因此,每次您创建视图(刷新页面或更改视图并返回“购物车”视图)时,您都会调用 Vuex 并获取您需要的数据。 如果你有comutped:{...mapGetters['cart'] },你就不能有data(){return{cart}}

我希望它有效并且对你有所帮助。

【讨论】:

    猜你喜欢
    • 2017-09-04
    • 1970-01-01
    • 1970-01-01
    • 2020-02-01
    • 2018-05-07
    • 2022-12-11
    • 2021-09-29
    • 1970-01-01
    • 2018-11-29
    相关资源
    最近更新 更多