一、加入购物车的两种策略
1、加入购物车接口
在 src/restful/api.js 中写入添加购物车接口:
// 加入购物车的接口
export const shopCart = (params) => {
return Axios.post('user/shop_cart/create/', params).then(res=>res.data)
};
2、添加Axios的请求拦截器
Axios 的拦截器:在请求或响应被 then 或 catch 处理前拦截它们,说明文档:Axios使用说明。模板如下所示:
// 添加请求拦截器
axios.interceptors.request.use(function (config) {
// 在发送请求之前做些什么
return config;
}, function (error) {
// 对请求错误做些什么
return Promise.reject(error);
});
// 添加响应拦截器
axios.interceptors.response.use(function (response) {
// 对响应数据做点什么
return response;
}, function (error) {
// 对响应错误做点什么
return Promise.reject(error);
});
在项目 src/restful/api.js 中添加请求拦截器:
// 导入axios
import Axios from 'axios'
Axios.defaults.baseURL = 'https://www.luffycity.com/api/v1/'; // 设置公共url
// 添加请求拦截器
axios.interceptors.request.use(function (config) {
// 在发送请求之前做些什么
if (localStorage.getItem('access_token')){
// 配置的默认值/defaults
config.defaults.headers.common['Authorization'] = localStorage.getItem('access_token');
}
return config;
}, function (error) {
// 对请求错误做些什么
return Promise.reject(error);
});
改写CouseDetail页面中加入购物车事件:
二、购物车页面实现
三、购物车页面数据展示
四、购物车页面数据响应