本案例主要针对Vuex共享数据的练习以及父子组件数据的共享。
脚手架新建项目 (注意:勾选vuex)
版本说明:
vue2 vue-router3 vuex3
vue3 vue-router4 vuex4/pinia
vue create vue-cart-demo
需求:
store/modules/cart.js
export default {
namespaced: true,
state () {
return {
list: []
}
},
}
store/index.js
import Vuex from 'vuex'
import Vue from 'vue'
import cart from './modules/cart'
Vue.use(Vuex)
const store = new Vuex.Store({
modules: {
cart
}
})
export default store
yarn global add json-server 或 npm i json-server -g
{
"cart": [
{
"id": 100001,
"name": "低帮城市休闲户外鞋天然牛皮COOLMAX纤维",
"price": 128,
"count": 1,
"thumb": "https://yanxuan-item.nosdn.127.net/3a56a913e687dc2279473e325ea770a9.jpg"
},
{
"id": 100002,
"name": "网易味央黑猪猪肘330g*1袋",
"price": 39,
"count": 14,
"thumb": "https://yanxuan-item.nosdn.127.net/d0a56474a8443cf6abd5afc539aa2476.jpg"
},
{
"id": 100003,
"name": "KENROLL男女简洁多彩一片式室外拖",
"price": 128,
"count": 2,
"thumb": "https://yanxuan-item.nosdn.127.net/eb1556fcc59e2fd98d9b0bc201dd4409.jpg"
},
{
"id": 100004,
"name": "云音乐定制IN系列intar民谣木吉他",
"price": 589,
"count": 1,
"thumb": "https://yanxuan-item.nosdn.127.net/4d825431a3587edb63cb165166f8fc76.jpg"
}
]
}
json-server --watch index.json
当服务启动后,可以访问http://localhost:3000/cart
获取数据
请求获取数据存入 vuex, 映射渲染
yarn add axios
import axios from 'axios'
export default {
namespaced: true,
state () {
return {
list: []
}
},
mutations: {
updateList (state, payload) {
state.list = payload
}
},
actions: {
async getList (ctx) {
const res = await axios.get('http://localhost:3000/cart')
ctx.commit('updateList', res.data)
}
}
}
App.vue
页面中调用 action, 获取数据import { mapState } from 'vuex'
export default {
name: 'App',
components: {
CartHeader,
CartFooter,
CartItem
},
created () {
this.$store.dispatch('cart/getList')
},
computed: {
...mapState('cart', ['list'])
}
}
cart-item.vue
{{item.name}}
¥{{item.price}}
{{item.count}}
{{item.count}}
onBtnClick (step) {
const newCount = this.item.count + step
if (newCount < 1) return
// 发送修改数量请求
this.$store.dispatch('cart/updateCount', {
id: this.item.id,
count: newCount
})
}
async updateCount (ctx, payload) {
await axios.patch('http://localhost:3000/cart/' + payload.id, {
count: payload.count
})
ctx.commit('updateCount', payload)
}
mutations: {
...,
updateCount (state, payload) {
const goods = state.list.find((item) => item.id === payload.id)
goods.count = payload.count
}
},
getters: {
total(state) {
return state.list.reduce((p, c) => p + c.count, 0);
},
totalPrice (state) {
return state.list.reduce((p, c) => p + c.count * c.price, 0);
},
},