Vue页面刷新后如何读取Cookie中cart_guid并将购物车数据同步到Vuex Store
实现方案
1. 完善cartHelper逻辑,初始化时读取Cookie中留存的cart_guid
你当前的cartHelper默认cookieValue为空,不会主动读取Cookie中已存储的cart_guid,先补充这部分逻辑:
// 新增读取Cookie的工具方法 function getCookie(name) { const value = `; ${document.cookie}`; const parts = value.split(`; ${name}=`); if (parts.length === 2) return parts.pop().split(';').shift(); } let cartHelper = { cartCookieName: "_cart", // 初始化时直接从Cookie读取已有的cart_guid cookieValue: getCookie("_cart") || "", // 其余原有代码保持不变 getCart: function (callback = undefined) { return apiHelper.getRequest( "/carts", (response) => { document.cookie = `${this.cartCookieName}=${response.data.attributes.cart_guid};`; this.cookieValue = response.data.attributes.cart_guid; if (callback) { callback(response); } } ) }, addToCart: function (product, variation_id, amount, callback = undefined) { if(this.cookieValue == "") { this.getCart(() => { this._addToCart(product, variation_id, amount, callback); }); } else { this._addToCart(product, variation_id, amount, callback) } }, _addToCart(product, variation_id, amount, callback = undefined) { return apiHelper.postRequest( `/carts/${this.cookieValue}/add-item`, (response) => { document.cookie = `${this.cartCookieName}=${response.data.attributes.cart_guid};`; if (callback) { callback(response); } }, { product_id: product, variation_id: variation_id, amount: amount, } ) }, } export default cartHelper;
2. 新增Vuex初始化购物车的Action
复用你已有的ADD_TO_CART mutation,新增初始化拉取购物车的action:
// 引入你封装的cartHelper,路径替换成你实际的文件路径 import cartHelper from '@/utils/cartHelper' // 在Vuex的actions中新增如下方法 export const initCart = ({commit}) => { // 仅当Cookie中存在cart_guid时才发起请求 if (cartHelper.cookieValue) { cartHelper.getCart((response) => { commit('ADD_TO_CART', {cart: response.data}) }) } } // 你原有其余action代码保持不变 export const addProductToCart = ({commit}, {cart}) => { commit('ADD_TO_CART', {cart}); }
3. 选择初始化逻辑的执行时机
页面刷新后需要优先执行初始化逻辑拉取购物车数据,推荐两个常用的执行位置:
方案A:在根组件App.vue的生命周期中调用
// App.vue export default { name: 'App', created() { this.$store.dispatch('initCart') }, // 其余原有逻辑保持不变 }
方案B:在main.js中Vue实例挂载前调用
// main.js import Vue from 'vue' import App from './App.vue' import store from './store' // 页面加载后先执行购物车初始化 store.dispatch('initCart') new Vue({ store, render: h => h(App) }).$mount('#app')
如果你的后端拉取购物车的接口需要主动在路径中传入cart_guid,只需要将cartHelper中getCart方法的请求路径调整为/carts/${this.cookieValue}即可,其余逻辑无需改动。
内容的提问来源于stack exchange,提问作者magic bean
相关产品推荐
相关产品推荐

