需求:当点击了加入购物车按键后,把商品添加到购物车中。
步骤:
- 先获取商品的数据,保存到仓库中
- 将数据保存到本地存储
- 在购物车页面,从本地进行调用数据
- 进行页面渲染
页面组成:
<HeaderW>:头部,有两个<router-link>
<Context>:组件展示区,使用<router-view>,有两个组件(Books---图书列表,Car---购物车)
前期准备工作:
- 先安装路由和Vuex
npm install vue-router@3 --save
npm install vuex@3 --save
- 配置路由
(1)创建router文件夹,在里面创建index.js文件
import VueRouter from 'vue-router'
import car from '../components/car.vue'
import header from '../components/HeaderW.vue'
import Books from '../components/Books.vue'
export default new VueRouter({
routes:[
{
path:'/car',
component:car
},
{
path:'/header',
component:header
},
{
path:'/books',
component:Books
}
]
})
(2)在main.js中引入
import VueRouter from 'vue-router'
import App from './App.vue'
import Vue from 'vue'
import router from './router'
Vue.use(VueRouter)
new Vue({
render: h => h(App),
router,
}).$mount('#app')
- 配置store
(1)创建store文件夹,在里面创建index.js文件
import Vue from 'vue'
import Vuex from 'vuex'
Vue.use(Vuex)
const actions={
}
const mutations={
}
const state={
}
export default new Vuex.Store({
actions,
mutations,
state
})
(2) 在main.js中引入store
import store from './store/index'
new Vue({
render: h => h(App),
router,
store
}).$mount('#app')
操作步骤:
1.给添加到购物车按钮,添加点击事件
//在图书列表Books组件里
<td><button @click="addCart(book)">添加到购物车</button></td>
2.当点击之后,就派发请求,获取数据,把数据传给服务器
//在图书列表Books组件里
methods: {
addCart(book) {
book.count = 1; //默认情况下购买数量都为1
this.$store.commit("ADDCAR", book);
// this.$router.push("/car");
},
},
3.配置仓库里的数据
//在store/index.js中
const actions={
}
const mutations={
// 这里的book就是使用commit传过来的参数
ADDCAR(state,book){
// 下面进行去重判断
// 当点击商品时,第一次点击是添加商品,第二次点击表示商品数量的添加
var flag=false//首先设置默认是没有数据的
state.carList.some(item=>{//使用some检测传过来的数据的id是不是和本地存储的一样,如果一样则数量加加
if(item.id==book.id){
item.count++
flag=true
}
})
// 默认情况下,没有数据时,直接添加商品
if(!flag){
state.carList.push(book)
}
// 使用本地存储数据
localStorage.setItem('carList',JSON.stringify(state.carList))
}
}
const state={
carList:[]
}
4.在购物车页面,获取数据
//在car.vue中
data() {
return {
cartList: [],
};
},
created() {
this.cartList = this.$store.state.carList;
},
5.渲染购物车页面
<tr v-for="(book, index) in cartList" :key="index">
<td><input type="checkbox" v-model="book.check" /></td>
<td>{{ index + 1 }}</td>
<td>{{ book.title }}</td>
<td>¥{{ book.price }}</td>
<td>
<button :disabled="book.count===0" @click="book.count--">-</button>
{{ book.count }}
<button @click="book.count++">+</button>
</td>
<td><button>删除</button></td>
</tr>
注意:这里的传过来的数据是book,book里面有id,type,title,price,count这些数据。