一、核心概念 - state 状态
目标:明确如何给仓库提供数据,如何使用仓库的数据
1.提供数据
State提供唯一的公共数据源,所有共享的数据都要统一放到Store中的State中存储。 在state
对象中可以添加我们要共享的数据。

2.使用数据
① 通过 store 直接访问

② 通过辅助函数


**二、**核心概念 - mutations
1. 目标:明确 vuex 同样遵循单向数据流,组件中不能直接修改仓库的数据
通过 strict: true 可以开启严格模式

(1)定义 mutations 对象,对象中存放修改 state 的方法

(2)组件中提交调用 mutations

2. 目标:掌握 mutations 传参语法
提交 mutation 是可以传递参数的 `this.$store.commit( 'xxx', 参数 )`
(1)提供 mutation 函数 (带参数 - 提交载荷 payload )

(2)页面中提交调用 mutation

Tips: 提交参数只能一个,如果有多个参数,包装成一个对象传递

**3.**核心概念 - mutations - 练习
(1)目标:减法功能,巩固 mutations 传参语法

(2)目标:实时输入,实时更新,巩固 mutations 传参语法

三、辅助函数 - mapMutations
目标:掌握辅助函数 mapMutations,映射方法
mapMutations和mapState很像,它是把位于mutations中的方法提取了出来,映射到组件methods

四、核心概念 - actions
目标:明确 actions 的基本语法,处理异步操作。
需求: 一秒钟之后, 修改 state 的 count 成 666。
说明:mutations 必须是同步的 (便于监测数据变化,记录调试)

五、辅助函数 - mapActions
目标:掌握辅助函数 mapActions,映射方法
mapActions 是把位于 actions中的方法提取了出来,映射到组件methods中

六、核心概念 - getters
目标:掌握核心概念 getters 的基本语法 (类似于计算属性)
说明:除了state之外,有时我们还需要从state中派生出一些状态,这些状态是依赖state的,此时
会用到getters
例如:state中定义了list,为 1-10 的数组,组件中,需要显示所有大于5的数据

**1.**定义 getters

**2.**访问getters
(1)通过 store 访问 getters

(2)通过辅助函数 mapGetters 映射

七、核心概念 - 模块 module (进阶语法)
1.目标:掌握核心概念 module 模块的创建
(1)由于vuex使用单一状态树,应用的所有状态会集中到一个比较大的对象。当应用变得非常复
杂时,store对象就有可能变得相当臃肿。(当项目变得越来越大的时候,Vuex会变得越来越
难以维护)

(2)模块拆分:user模块: store/modules/user.js

2.目标:掌握模块中 state 的访问语法
尽管已经分模块了,但其实子模块的状态,还是会挂到根级别的state中,属性名就是模块名使用
模块中的数据:
(1)直接通过模块名访问 $store.state.模块名.xxx
(2)通过 mapState 映射
默认根级别的映射 mapState([ 'xxx' ])
子模块的映射 mapState('模块名', ['xxx']) - 需要开启命名空间

3.目标:掌握模块中 getters 的访问语法
使用模块中 getters 中的数据:
(1)直接通过模块名访问 $store.getters['模块名/xxx ']
(2)通过 mapGetters 映射
默认根级别的映射 mapGetters([ 'xxx' ])
子模块的映射 mapGetters('模块名', ['xxx']) - 需要开启命名空间

4.目标:掌握模块中 mutation 的调用语法
注意:默认模块中的 mutation 和 actions 会被挂载到全局,需要开启命名空间,才会挂载到子模
块。 调用子模块中 mutation:
(1)直接通过 store 调用 $store.commit('模块名/xxx ', 额外参数)
(2)通过 mapMutations 映射
默认根级别的映射 mapMutations([ 'xxx' ])
子模块的映射 mapMutations('模块名', ['xxx']) - 需要开启命名空间

5.目标:掌握模块中 action 的调用语法 (同理 - 直接类比 mutation 即可)
注意:默认模块中的 mutation 和 actions 会被挂载到全局,需要开启命名空间,才会挂载到子模
块。 调用子模块中 action :
(1)直接通过 store 调用 $store.dispatch('模块名/xxx ', 额外参数)
(2)通过 mapActions 映射
默认根级别的映射 mapActions([ 'xxx' ])
子模块的映射 mapActions('模块名', ['xxx']) - 需要开启命名空间

javascript
// ./store/index.js
// 这里面存放的就是 vuex 相关的核心代码
import Vue from 'vue'
import Vuex from 'vuex'
import user from './modules/user'
import setting from './modules/setting'
// 插件安装
Vue.use(Vuex)
// 创建仓库(空仓库)
const store = new Vuex.Store({
// 严格模式(有利于初学者,检测不规范的代码 => 上线时需要移除)
strict: true,
// 1. 通过 state 可以提供数据(所以组件共享的数据)
state: {
title: '仓库大标题',
count: 100,
list: [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
},
// 2. 通过 mutation 可以提供修改数据的方法
mutations: {
// 所有 mutation 函数,第一个参数,都是 state
// 注意点:mutation 参数有且只能有一个,如果需要多个参数,包装成一个对象
addCount (state, n) {
// 修改数据
state.count += n
},
subCount (state, n) {
state.count -= n
},
changeCount (state, newCount) {
state.count = newCount
},
changeTitle (state, newTitle) {
state.title = newTitle
}
},
// 3. actions 处理异步,
// 注意:不能直接操作 state. 操作state. 还是需要 commit mutation
actions: {
// context 上下文(此处未分模块,可以当成store仓库)
// context.commit('mutation名字',额外参数)
changeCountAction (context, num) {
// 这里是setTimeout模拟异步,以后大部分场景是发请求
setTimeout(() => {
context.commit('changeCount', num)
}, 1000)
}
},
// 4.getters 类似于计算属性
getters: {
// 注意点:
// 1. 形参第一个参数,就是state
// 2. 必须有返回值,返回值就是getters的值
filterList (state) {
return state.list.filter(item => item > 5)
}
},
// 5.modules 模块
modules: {
user,
setting
}
})
// 导出给main.js使用
export default store
javascript
// ./App.vue
<template>
<div id="app">
<h1>
根组件
- {{ title }}
- {{ count }}
</h1>
<input :value="count" @input="handleInput" type="text">
<Son1></Son1>
<hr>
<Son2></Son2>
</div>
</template>
<script>
import Son1 from './components/Son1.vue'
import Son2 from './components/Son2.vue'
import { mapState } from 'vuex'
// console.log(mapState(['count', 'title']))
export default {
name: 'app',
created () {
// console.log(this.$router) // 没配
console.log(this.$store.state.count)
},
computed: {
...mapState(['count', 'title'])
},
data: function () {
return {
}
},
methods: {
handleInput (e) {
// 1. 实时获取输入框的值
const num = +e.target.value
// 2. 提交 mutation ,调用 mutation 函数
this.$store.commit('changeCount', num)
}
},
components: {
Son1,
Son2
}
}
</script>
<style>
#app {
width: 600px;
margin: 20px auto;
border: 3px solid #ccc;
border-radius: 3px;
padding: 10px;
}
</style>
javascript
// ./components/Son1.vue
<template>
<div class="box">
<h2>Son1 子组件</h2>
从vuex中获取的值: <label>{{ $store.state.count }}</label>
<br>
<button @click="handleAdd(1)">值 + 1</button>
<button @click="handleAdd(5)">值 + 5</button>
<button @click="handleAdd(10)">值 + 10</button>
<button @click="handleChange">1秒后修改成666</button>
<button @click="changeFn">改标题</button>
<hr>
<!-- 计算属性getters -->
<div>{{ $store.state.list }}</div>
<div>{{ $store.getters.filterList }}</div>
<hr>
<!-- 测试访问模块中的state - 原生 -->
<div>{{ $store.state.user.userInfo.name }}</div>
<button @click="updateUser">更新个人信息</button>
<button @click="updateUser2">1秒后更新个人信息</button>
<div>{{ $store.state.setting.theme}}</div>
<button @click="updateTheme">更新主题色</button>
<hr>
<!-- 测试访问模块中的getters - 原生 -->
<div>{{ $store.getters['user/UpperCaseName'] }}</div>
</div>
</template>
<script>
export default {
name: 'Son1Com',
created () {
console.log(this.$store.getters)
},
methods: {
updateUser () {
// $store.commit('模块名/mutation名', 额外传参)
this.$store.commit('user/setUser', {
name: 'ytl',
age: 20
})
},
updateUser2 () {
// 如何调用action dispatch
this.$store.dispatch('user/setUserSecond', {
name: 'qjl',
age: 28
})
},
updateTheme () {
this.$store.commit('setting/setTheme', 'blue')
},
handleAdd (n) {
// 错误代码(vue 默认不会检测,需要监测成本,开启严格模式即可)
// this.$store.state.count++
// console.log(this.$store.state.count)
// 应该通过 mutation 核心概念,进行修改数据
// 需要提供调用 mutation
// this.$store.commit('addCount')
// console.log(n)
// 调用带参数的 mutation 函数
this.$store.commit('addCount', n)
},
changeFn () {
this.$store.commit('changeTitle', '灰太狼')
},
handleChange () {
// 调用action
// this.$store.dispatch('action名字', 额外参数)
this.$store.dispatch('changeCountAction', 666)
}
}
}
</script>
<style lang="css" scoped>
.box{
border: 3px solid #ccc;
width: 400px;
padding: 10px;
margin: 20px;
}
h2 {
margin-top: 10px;
}
</style>
javascript
// ./components/Son2.vue
<template>
<div class="box">
<h2>Son2 子组件</h2>
从vuex中获取的值:<label>{{ count }}</label>
<br />
<button @click="subCount(1)">值 - 1</button>
<button @click="subCount(5)">值 - 5</button>
<button @click="subCount(10)">值 - 10</button>
<button @click="chanageCountAction(888)">1秒后修改成888</button>
<button @click="changeTitle('我是灰太狼')">改标题</button>
<hr>
<div>{{ filterList }}</div>
<hr>
<!-- 访问模块中的state -->
<div>{{ user.userInfo.name }}</div>
<div>{{ setting.theme }}</div>
<hr>
<!-- 访问模块中的state -->
<div>user模块数据:{{ userInfo}}</div>
<button @click="setUser({ name: 'hettl', age: 40})">更新个人信息</button>
<button @click="setUserSecond({ name: 'hettl', age: 40})">1秒后更新个人信息</button>
<div>setting模块数据:{{ theme }} - {{ desc }}</div>
<button @click="setTheme('blue')">更新主题色</button>
<hr>
<!-- 访问模块中的getters -->
<div>{{ UpperCaseName }}</div>
<div></div>
</div>
</template>
<script>
import { mapState, mapMutations, mapActions, mapGetters } from 'vuex'
export default {
name: 'Son2Com',
computed: {
// mapState 和 mapActions 都是映射属性
...mapState(['count', 'user', 'setting']),
...mapState('user', ['userInfo']),
...mapState('setting', ['theme', 'desc']),
...mapGetters(['filterList']),
...mapGetters('user', ['UpperCaseName'])
},
methods: {
// mapState 和 mapActions 都是映射方法
// 全局级别的映射
...mapMutations(['subCount', 'changeTitle']),
...mapActions(['chanageCountAction']),
// 分模块的映射
...mapMutations('setting', ['setTheme']),
...mapMutations('user', ['setUser']),
...mapActions('user', ['setUserSecond'])
// handleSub (n) {
// this.subCount(n)
// }
}
}
</script>
<style lang="css" scoped>
.box {
border: 3px solid #ccc;
width: 400px;
padding: 10px;
margin: 20px;
}
h2 {
margin-top: 10px;
}
</style>
javascript
// ./store/modules/user.js
// user模块
const state = {
userInfo: {
name: 'htl',
age: 18
},
score: 100
}
const mutations = {
setUser (state, newUserInfo) {
state.userInfo = newUserInfo
}
}
const actions = {
setUserSecond (context, newUserInfo) {
// 将异步在action中进行封装
setTimeout(() => {
// 调用mutation context上下文,默认提交的就是直接模块的action和mutation
context.commit('setUser', newUserInfo)
}, 1000)
}
}
const getters = {
// 分模块后,state指代子模块的state
UpperCaseName (state) {
return state.userInfo.name.toUpperCase()
}
}
export default {
namespaced: true,
state,
mutations,
actions,
getters
}
javascript
// ./store/modules/setting.js
// setting模块
const state = {
theme: 'light', // 主题色
desc: '测试demo'
}
const mutations = {
setTheme (state, newTheme) {
state.theme = newTheme
}
}
const actions = {}
const getters = {}
export default {
namespaced: true,
state,
mutations,
actions,
getters
}