一、加入购物车的两种策略
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 中添加请求拦截器:
import Axios from 'axios' // 导入axios Axios.defaults.baseURL = 'https://www.luffycity.com/api/v1/'; // 设置公共url // 添加请求拦截器 Axios.interceptors.request.use(function (config) { // 在发送请求之前做些什么 if (localStorage.getItem('access_token')){ // 配置的默认值/defaults // Axios.defaults.headers.common['Authorization'] = localStorage.getItem('access_token'); console.log(config.headers); config.headers.Authorization = localStorage.getItem('access_token'); } return config; }, function (error) { // 对请求错误做些什么 return Promise.reject(error); });
查看控制台 config.headers 中包含的信息:
3、改写CouseDetail页面中购物车事件
(1)课程信息获取
添加购物车首先要获取当前课程信息。
<script> export default { name: 'CourseDetail', data(){ return { // 声明变量存储数据 coursedetailtop: {}, // 课程顶部详情数据 content: "", // currentIndex: 0, // 为0时,页面刷新默认选择了第一项 currentIndex: null, // 默认不选择 prices: [] } }, methods: { // 加入购物车事件 addShopCart(){ if(this.currentIndex){ // 判断当前currentIndex是否有值 if(window.localStorage.getItem('access_token')){ // 判断用户是否登录 // 添加到购物车 alert('买吧'); let course = { courseId: this.$route.params.detailId, // 课程id validPeriodId: this.prices[this.currentIndex].valid_period, }; console.log(course); // this.$http.shopCart(); } else { // 跳转登录页面 // 使用编程式导航来跳转// 代码略 </script>
在控制台查看打印的course对象:
(2)添加购物车事件
methods: { // 加入购物车事件 addShopCart(){ if(this.currentIndex){ // 判断当前currentIndex是否有值 if(window.localStorage.getItem('access_token')){ // 判断用户是否登录 // 添加到购物车 alert('买吧'); let course = { courseId: this.$route.params.detailId, //