状态管理工具
,状态就是数据。管理 vue 通用的数据 (多组件共享的数据)
例如:购物车数据 个人信息数据很多个组件
来使用 (个人信息)共同维护
一份数据 (购物车)数据集中化管理
响应式变化
vue create vuex-demo
|-components
|--Son1.vue
|--Son2.vue
|-App.vue
App.vue
引入 Son1 和 Son2 子组件
根组件
main.js
import Vue from 'vue'
import App from './App.vue'
Vue.config.productionTip = false
new Vue({
render: h => h(App)
}).$mount('#app')
components/Son1.vue
<template>
<div class="box">
<h2>Son1 子组件h2>
从vuex中获取的值: <label>label>
<br>
<button>值 + 1button>
div>
template>
<script>
export default {
name: 'Son1Com'
}
script>
<style lang="css" scoped>
.box{
border: 3px solid #ccc;
width: 400px;
padding: 10px;
margin: 20px;
}
h2 {
margin-top: 10px;
}
style>
components/Son2.vue
<template>
<div class="box">
<h2>Son2 子组件h2>
从vuex中获取的值:<label>label>
<br />
<button>值 - 1button>
div>
template>
<script>
export default {
name: 'Son2Com'
}
script>
<style lang="css" scoped>
.box {
border: 3px solid #ccc;
width: 400px;
padding: 10px;
margin: 20px;
}
h2 {
margin-top: 10px;
}
style>
yarn add vuex@3 或者 npm i vuex@3
router/index.js
类似)store/index.js
中,使用Vuex// 导入 vue
import Vue from 'vue'
// 导入 vuex
import Vuex from 'vuex'
// vuex也是vue的插件, 需要use一下, 进行插件的安装初始化
Vue.use(Vuex)
// 创建仓库 store
const store = new Vuex.Store()
// 导出仓库
export default store
import Vue from 'vue'
import App from './App.vue'
import store from './store'
Vue.config.productionTip = false
new Vue({
render: h => h(App),
store
}).$mount('#app')
created(){
console.log(this.$store)
}
提供
数据,如何 使用
仓库的数据公共数据源
,所有共享的数据都要统一放到 Store 中的 State 中存储。// 创建仓库 store
const store = new Vuex.Store({
// state 状态, 即数据, 类似于vue组件中的data,
// 区别:
// 1.data 是组件自己的数据,
// 2.state 中的数据整个vue项目的组件都能访问到
state: {
count: 101
}
})
获取 store:
1.Vue模板中获取 this.$store
2.js文件中获取 import 导入 store
模板中: {{ $store.state.xxx }}
组件逻辑中: this.$store.state.xxx
JS模块中: store.state.xxx
state的数据 - {{ $store.state.count }}
state的数据 - {{ count }}
// 把state中数据,定义在组件内的计算属性中
computed: {
count () {
return this.$store.state.count
}
}
//main.js
import store from "@/store"
console.log(store.state.count)
自动
映射到 组件的计算属性中import { mapState } from 'vuex'
computed: {
...mapState(['count'])
}
count () {
return this.$store.state.count
}
<div> state的数据:{{ count }}</div>
错误写法
),但是vue默认不会监测
,监测需要成本
methods:{
handleAdd (n) {
// 错误代码(vue默认不会监测,监测需要成本)
this.$store.state.count++
// console.log(this.$store.state.count)
},
}
strict: true
可以开启严格模式,开启严格模式后,直接修改state中的值会报错只能通过mutations
,并且mutations必须是同步
的const store = new Vuex.Store({
state: {
count: 0
},
// 定义mutations
mutations: {
// 第一个参数是当前store的state属性
addCount (state) {
state.count += 1
}
}
})
this.$store.commit('addCount')
提交 mutation 是可以传递参数的 this.$store.commit( 'xxx', 参数 )
带参数的mutations操作流程如下:
mutations: {
...
addCount (state, count) {
state.count = count
}
},
handle ( ) {
this.$store.commit('addCount', 10)
}
this.$store.commit('addCount', {
count: 10,
...
})
export default {
methods:{
subCount (n) {
this.$store.commit('addCount', n)
},
}
}
mutations:{
subCount (state, n) {
state.count -= n
},
}
export default {
methods: {
handleInput (e) {
// 1. 实时获取输入框的值
const num = +e.target.value
// 2. 提交mutation,调用mutation函数
this.$store.commit('changeCount', num)
}
}
}
mutations: {
changeCount (state, newCount) {
state.count = newCount
}
},
mutations中的方法
映射到methods
中import { mapMutations } from 'vuex'
methods: {
...mapMutations(['addCount'])
}
methods: {
// commit(方法名, 载荷参数)
addCount () {
this.$store.commit('addCount')
}
}
<button @click="addCount">值+1</button>
便于监测数据的变化,记录调试
)actions: {
setAsyncCount (context, num) {
// 一秒后, 给一个数, 去修改 num
setTimeout(() => {
context.commit('changeCount', num)
}, 1000)
}
},
this.$store.dispatch('setAsyncCount', 200)
actions中的方法
映射到组件methods
中import { mapActions } from 'vuex'
methods: {
...mapActions(['changeCountAction'])
}
methods: {
changeCountAction (n) {
this.$store.dispatch('changeCountAction', n)
},
}
<button @click="changeCountAction(200)">+异步</button>
派生出一些状态
,这些状态是依赖state的,此时会用到gettersstate: {
list: [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
}
getters: {
// (1) getters函数的第一个参数是 state
// (2) getters函数必须要有返回值
filterList: state => state.list.filter(item => item > 5)
}
{{ $store.getters.filterList }}
getters中的属性
映射到组件computed
中computed: {
...mapGetters(['filterList'])
}
computed: {
filterList(){
return $store.getters.filterList;
}
}
{{ filterList }}
定义两个模块 user
和 setting
modules/user.js
:user中管理用户的信息状态 userInfo
const state = {
userInfo: {
name: 'zs',
age: 18
}
}
const mutations = {}
const actions = {}
const getters = {}
export default {
namespaced: true,
state,
mutations,
actions,
getters
}
modules/setting.js
:setting中管理项目应用的 主题色 theme,描述 descconst state = {
theme: 'dark'
desc: '描述真呀真不错'
}
const mutations = {}
const actions = {}
const getters = {}
export default {
namespaced: true,
state,
mutations,
actions,
getters
}
store/index.js
文件中的modules配置项中,注册这两个模块import user from './modules/user'
import setting from './modules/setting'
const store = new Vuex.Store({
modules:{
user,
setting
}
})
使用模块中的数据
通过模块名访问:$store.state.模块名.xxx
通过 mapState 映射:
默认根级别的映射:mapState([ 'xxx' ])
子模块的映射 :mapState('模块名', ['xxx'])
- 需要开启命名空间 namespaced:true(对应模块文件中开启)
export default {
namespaced: true,
state,
mutations,
actions,
getters
}
代码演示
$store.state.user.userInfo.name
...mapState('user', ['userInfo']),
...mapState('setting', ['theme', 'desc']),
使用模块getters数据
通过模块名访问:$store.getters['模块名/xxx ']
通过 mapGetters 映射
mapGetters([ 'xxx' ])
mapGetters('模块名', ['xxx'])
- 需要开启命名空间代码实现
modules/user.js
const getters = {
// 分模块后,state指代子模块的state
UpperCaseName (state) {
return state.userInfo.name.toUpperCase()
}
}
<div>{{ $store.getters['user/UpperCaseName'] }}</div>
computed:{
...mapGetters('user', ['UpperCaseName'])
}
注意:默认模块中的 mutation 和 actions 会被挂载到全局,需要开启命名空间
,才会挂载到子模块。
使用模块mutations方法
通过 store 调用:$store.commit('模块名/xxx ', 额外参数)
通过 mapMutations 映射
mapMutations([ 'xxx' ])
mapMutations('模块名', ['xxx'])
- 需要开启命名空间代码实现
modules/user.js
const mutations = {
setUser (state, newUserInfo) {
state.userInfo = newUserInfo
}
}
modules/setting.js
const mutations = {
setTheme (state, newTheme) {
state.theme = newTheme
}
}
export default {
methods: {
updateUser () {
// $store.commit('模块名/mutation名', 额外传参)
this.$store.commit('user/setUser', {
name: 'xiaowang',
age: 25
})
},
updateTheme () {
this.$store.commit('setting/setTheme', 'pink')
}
}
}
methods:{
// 分模块的映射
...mapMutations('setting', ['setTheme']),
...mapMutations('user', ['setUser']),
}
注意:默认模块中的 mutation 和 actions 会被挂载到全局,需要开启命名空间
,才会挂载到子模块。
使用模块actions方法
$store.dispatch('模块名/xxx ', 额外参数)
mapActions([ 'xxx' ])
mapActions('模块名', ['xxx'])
- 需要开启命名空间代码实现
modules/user.js
const actions = {
setUserSecond (context, newUserInfo) {
// 将异步在action中进行封装
setTimeout(() => {
// 调用mutation context上下文,默认提交的就是自己模块的action和mutation
context.commit('setUser', newUserInfo)
}, 1000)
}
}
methods:{
updateUser2 () {
// 调用action dispatch
this.$store.dispatch('user/setUserSecond', {
name: 'xiaohong',
age: 28
})
},
}
<button @click="setUserSecond({ name: 'xiaoli', age: 80 })">一秒后更新信息</button>
methods:{
...mapActions('user', ['setUserSecond'])
}
直接使用
state --> $store.state.模块名.数据项名
getters --> $store.getters[‘模块名/属性名’]
mutations --> $store.commit(‘模块名/方法名’, 其他参数)
actions --> $store.dispatch(‘模块名/方法名’, 其他参数)
借助辅助方法使用
import { mapXxxx, mapXxx } from ‘vuex’
…mapState、…mapGetters放computed中;
…mapMutations、…mapActions放methods中;
…mapXxxx(‘模块名’, [‘数据项|方法’])
…mapXxxx(‘模块名’, { 新的名字: 原来的名字 })
数据存 vuex
修改数据
动态计算
总价和总数量勾选vuex
vue create vue-cart-demo
import Vue from 'vue'
import App from './App.vue'
import store from './store'
Vue.config.productionTip = false
new Vue({
store,
render: h => h(App)
}).$mount('#app')
import Vue from 'vue'
import Vuex from 'vuex'
Vue.use(Vuex)
export default new Vuex.Store({
state: {
},
getters: {
},
mutations: {
},
actions: {
},
modules: {
}
})
购物车案例
低帮城市休闲户外鞋天然牛皮COOLMAX纤维
¥128
1
store/modules/cart.js
export default {
namespaced: true,
state () {
return {
list: []
}
},
}
store/index.js
import Vue from 'vue'
import Vuex from 'vuex'
import cart from './modules/cart'
Vue.use(Vuex)
export default new Vuex.Store({
modules: {
cart
}
})
export default store
json-server
(全局工具仅需要安装一次),官网地址:https://www.npmjs.com/package/json-servernpm i json-server -g
{
"cart": [{
"id": 100001,
"name": "低帮城市休闲户外鞋天然牛皮COOLMAX纤维",
"price": 128,
"count": 5,
"thumb": "https://bluecusliyoupicrep.oss-cn-hangzhou.aliyuncs.com/202307271039546.png"
},
{
"id": 100002,
"name": "网易味央黑猪猪肘330g*1袋",
"price": 39,
"count": 10,
"thumb": "https://bluecusliyoupicrep.oss-cn-hangzhou.aliyuncs.com/202307271039546.png"
},
{
"id": 100003,
"name": "KENROLL男女简洁多彩一片式室外拖",
"price": 128,
"count": 3,
"thumb": "https://bluecusliyoupicrep.oss-cn-hangzhou.aliyuncs.com/202307271039546.png"
},
{
"id": 100004,
"name": "云音乐定制IN系列intar民谣木吉他",
"price": 589,
"count": 1,
"thumb": "https://bluecusliyoupicrep.oss-cn-hangzhou.aliyuncs.com/202307271039546.png"
}
],
"friends": [{
"id": 1,
"name": "zs",
"age": 18
},
{
"id": 2,
"name": "ls",
"age": 19
},
{
"id": 3,
"name": "ww",
"age": 20
}
]
}
json-server --watch index.json
yarn add axios
store/modules/cart.js
)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
)import { mapState } from 'vuex'
export default {
name: 'App',
components: {
CartHeader,
CartFooter,
CartItem
},
created () {
this.$store.dispatch('cart/getList')
},
computed: {
...mapState('cart', ['list'])
}
}
App.vue
)
components/cart-item.vue
{{item.name}}
¥{{item.price}}
{{item.count}}
components/cart-item.vue
)
{{item.count}}
components/cart-item.vue
)onBtnClick (step) {
const newCount = this.item.count + step
if (newCount < 1) return
// 发送修改数量请求
this.$store.dispatch('cart/updateCount', {
id: this.item.id,
count: newCount
})
}
store/modules/cart.js
)async updateCount (ctx, payload) {
await axios.patch('http://localhost:3000/cart/' + payload.id, {
count: payload.count
})
ctx.commit('updateCount', payload)
}
store/modules/cart.js
)mutations: {
...,
updateCount (state, payload) {
const goods = state.list.find((item) => item.id === payload.id)
goods.count = payload.count
}
},
store/modules/cart.js
)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);
},
},
components/cart-footer.vue
)