vuex总结起来无非是:
存:mutations(只能由它来操作state)
中转:actions(处理异步任务给mutation)
取:getters(类似计算属性,依赖state数据)
库:state(即数据源)
使用方法,建议使用展开运算符方式获取,
注意:解构出来的方法只能有一个参数,如果有多个要传递,可以使用数组或者对象。
import {mapState,mapMutations,mapActions,mapGetters}
computed: {
...mapState(['数据名']),
...mapGetters(['方法名']),
//另外一种方式
...mapState({message: state => state.goods.message })
}
methods: {
...mapActions(['方法名']),
...mapMutations(['方法名'])
}
代码实例
结合vue ui 图像界面创建vue项目
具体项目如下:
App.vue代码:
<template>
<div id="app">
<h2>郑哥的购物车:</h2>
<div>
商品名称:
<input @input="setName($event.target.value)" :value="good" />
</div>
<div>
商品价格:
<input @input="setPrice($event.target.value)" type="number" :value="price" />
</div>
<button @click="add">添加商品</button>
<ul>
<li v-for="item in goods" :key="item.id">
商品名称:{{item.name}},价格:{{item.price}}
<button @click="removeGood(item.id)">移除商品</button>
</li>
</ul>
<h3>总价:{{count}}</h3>
</div>
</template>
<script>
import { mapActions, mapMutations, mapState, mapGetters } from 'vuex'
export default {
created() {
//模拟异步
this.getDate()
console.log({...mapState({ good: state => state.goodInfo.name})})
},
methods: {
//获取商品列表异步方法
...mapActions(['getDate']),
//设置商品名称,设置商品价格,添加商品
...mapMutations(['setName', 'setPrice', 'addGood','removeGood']),
//添加商品
add() {
const { name, price } = this.goodInfo
//判断
if (!name.trim().length || !price) return alert('请书写完整')
//发起请求
this.addGood()
}
},
computed: {
//商品列表、要添加的商品信息
...mapState(['goods', 'goodInfo']),
//表单名字,表单价格
...mapState({ good: state => state.goodInfo.name ,price: state => state.goodInfo.price }),
//总价
...mapGetters(['count'])
}
}
</script>
<style>
</style>
store文件夹的index.js:
import Vue from 'vue'
import Vuex from 'vuex'
Vue.use(Vuex)
export default new Vuex.Store({
state: {
//商品
goods: [],
//表单数据
goodInfo: {
name:'',
id: 4,
price: null
}
},
mutations: {
//设置good数据
initDate(state, data) {
state.goods = data
console.log(data)
},
//设置商品名称
setName(state, name) {
state.goodInfo.name = name
},
//设置商品价格
setPrice(state, price) {
state.goodInfo.price = price
},
//添加商品
addGood(state) {
//设置id值
state.goodInfo.id++
//新增商品 必须深拷贝
state.goods.push({...state.goodInfo})
//清空
state.goodInfo.name =''
state.goodInfo.price = null
},
//移除商品
removeGood(state,id) {
var index = state.goods.findIndex(item => item.id ===id)
state.goods.splice(index,1)
}
},
actions: {
getDate(content) {
setTimeout(() => {
content.commit('initDate', require('../assets/data.json'))
}, 300)
}
},
getters: {
//商品总价
count(state) {
var count = 0
state.goods.forEach(item => count += Number(item.price))
return count
}
}
})
码云地址:git@gitee.com:xiao_zheng_123/vuex_shop.git
欢迎提出建议!!