vueX
1、认识应用状态管理
2、Vuex的基本使用
3、核心概念State
4、核心概念Getters
5、核心概念Mutations
6、核心概念Actions
7、核心概念Modules
状态管理
在程序中的需要处理各种各样的数据,这些数据需要保存在我们应用程序中某一个位置,对于这些数据的管理称之为状态管理。
vuex中的State可以向组件(Component)提供数据,但是组件无法直接修改state中的数据
修改State需在组件中触发一个Action,Action中可以触发网络请求,服务器返回数据 ,之后提交Mutations,最后同一修改State
如果没有网络请求,不需走Action,也需要提交到 Mutation
单一状态树
Vuex使用单一状态树
用一个对象就包含了全部的应用层级的状态
采用的是 SSOT,Single Source of Truth,也可以翻译成单一数据源;
这也意味着,每个应用将仅仅包含一个 store 实例
单状态树和模块化并不冲突
单一状态树的优势
- 如果你的状态信息是保存到多个Store对象中的,那么之后的管理和维护等等都会变的特别困难;
- 所以Vuex也使用了单一状态树来管理应用层级的全部状态
- 单一状态树能够让我们最直接的方式找到某个状态片段
- 而且在之后的维护和调试的过程中,也可以非常方便的管理和维护
state
在模板中使用;
<template>
<div class="about">
<h1>组合式api--{{$store.state.counter}}</h1>
<button @click="add">+1</button>
</div>
</template>
<script setup>
import {useStore} from "vuex";
const store = useStore()
function add(){
store.commit("add")
//store.state.counter++
}
</script>
在option api 中使用,比如computed
<template>
<div class="about">
<button @click="add">+1</button>
<h1>1{{storeCounter}}</h1>
</div>
</template>
<script>
export default {
computed:{
storeCounter(){
const newCount = this.$store.state.counter
return newCount
}
}
}
</script>
<script setup>
import {useStore} from "vuex";
const store = useStore()
function add(){
store.state.counter++
// store.commit("add")
}
</script>
在setup中使用
<template>
<div class="about">
<button @click="add">+1</button>
<h1>setupCounter--{{counter}}</h1>
</div>
</template>
<script setup>
import {toRefs} from "vue";
import {useStore} from "vuex";
const store = useStore()
const {counter} = toRefs(store.state)
function add(){
// store.state.counter++
store.commit("add")
}
</script>
store–index.js
import { createStore } from 'vuex'
const store = createStore({
state:() => {
return{
counter:1
}
},
mutations: {
add(state){
state.counter++
}
},
actions: {
},
modules: {
}
})
export default store
在模板中使用store,其他映射方法
组件获取状态
- 在前面我们已经学习过如何在组建中获取状态了
- 当然,如果觉得那种方法有点繁琐,我们可以使用计算机属性:
computed:{
storeCounter(){
const newCount = this.$store.state.counter
return newCount
}
}
- 但是,如果我们有多个状态都需要获取话,可以使用mapState的辅助函数:
- mapState的方式一:对象类型;
- mapState的方式二:数组类型;
- 也可以使用展开运算符和原有的computed混合在一起;
<template>
<div>
<p>方法一</p>
<p>计算机属性(映射状态:数组语法)</p>
<h2>fullname:{{ fullname }}</h2>
<p>方法二</p>
<p>在模板中直接使用多个状态</p>
<h2>counter:{{ $store.state.counter }}</h2>
<h2>avatarURL:{{ $store.state.avatarURL }}</h2>
<h2>level:{{ $store.state.level }}</h2>
<h2>name:{{ $store.state.name }}</h2>
<p>方法三</p>
<p>3.计算机属性(映射状态:对象语法)</p>
<h2>name:{{ sName }}</h2>
<h2>name:{{ sLevel }}</h2>
<p>4.1.setup中计算机属性(映射状态:对象语法)</p>
<h2>name:{{ cName }}</h2>
<h2>level:{{ cLevel }}</h2>
<p>4.2/4.3.setup中计算机属性(封装hook)/解构store.state</p>
<h2>name:{{ aName }}</h2>
<h2>name:{{ aLevel }}</h2>
<h2>counter:{{ aCounter }}</h2>
<button @click="addCounter">+1</button>
</div>
</template>
<script>
import {mapState} from "vuex";
export default {
name: "02_在模板中使用store的其他映射方法",
computed: {
// 方法一
fullname() {
return this.$store.state.counter
},
// 写法二
...mapState(["name", "level", "avatarURL"]),
// 写法三
...mapState({
sName: state => state.name,
sLevel: state => state.level
})
}
}
</script>
<script setup>
import {computed,toRefs} from "vue";
import useState from "@/hooks/useState";
import {mapState,useStore} from "vuex";
//方法四 4.1
const {name,level} = mapState(["name","level"])//拿到函数
const store = useStore()
const cName = computed(name.bind({$store:store}))
const cLevel = computed(level.bind({$store:store}))
//4.2 使用useState
// const {name,level} = useState(["name","level"])
//4.3 直接对 store.state 进行解构
// const store = useStore()
// toRefs保证得到的数据是响应式的
// const {name,level,counter} = toRefs(store.state)
const {name:aName,level:aLevel,counter:aCounter} = toRefs(store.state)
function addCounter(){
store.state.counter++
}
</script>
- 在setup中如果我们单个获取装是非常简单的:
- 通过useState拿到store后去获取某个状态即可
- 但是如果我们需要使用 mapstate 的功能呢
- 默认情况下,vuex并没有提供非常方便的使用mapState 的方式,这里我们进行了一个函数的封装
import {computed} from "vue";
import {useStore,mapState} from "vuex";
export default function useState(mapper){
const store = useStore()
const stateFnsObj = mapState(mapper)
const newState = {}
Object.keys(stateFnsObj).forEach(key =>{
newState[key] = computed(stateFnsObj[key].bind({$store:store}))
})
return newState
}
getters
getters的基本使用
<template>
<div class="app">
<h2>doubleCounter: {{ $store.getters.doubleCounter }}</h2>
<h2>totalAge: {{ $store.getters.totalAge }}</h2>
<h2>message: {{ $store.getters.message }}</h2>
<h2>1、找到id为2的用户:{{ $store.getters.getFriend1.name }}</h2>
<h2>2、找到id为2的用户:{{ $store.getters.getFriend1ById(2) }}</h2>
</div>
</template>
- 某些属性我们可能需要经过变化后来使用,这个时候可以使用getters
const store = createStore({
state:() => ({
counter:1,
name:"coderwhy",
level:100,
avatarURL:"http://xxxxxxxxx",
users:[
{id:1,name:"yyb",age:23},
{id:2,name:"kobe",age:43},
{id:3,name:"james",age:50}
]
}),
getters:{
doubleCounter(state){
return state.counter*2
},
totalAge(state){
return state.users.reduce((preValue,item) => {
return preValue + item.age
},0)
},
//在getters属性中,·获取其他getters
message(state,getters){
return `name:${state.name} level: ${state.level} totalAge: ${getters.totalAge}`
}
},
mutations: {
add(state){
state.counter++
}
},
- getters中的函数本身,可以返回一个函数,那么在使用的地方相当于可以调用这个函数:
getters:{
doubleCounter(state){
return state.counter*2
},
totalAge(state){
return state.users.reduce((preValue,item) => {
return preValue + item.age
},0)
},
//在getters属性中,·获取其他getters
message(state,getters){
return `name:${state.name} level: ${state.level} totalAge: ${getters.totalAge}`
},
//3.getters.是可以返回一个函数的,调用这个函数可以传入参数(了解)
getFriend1(state){
return state.users.find(item => item.id === 2)
},
getFriend1ById(state){
return function (id){
return state.users.find(item => item.id === id)
}
}
},
getter-mapGetter的映射方法
<template>
<div class="app">
<h2>方法1.1 doubleCounter: {{ doubleCounter }}</h2>
<h2>方法1.2 totalAge: {{ totalAge }}</h2>
<h2>方法2.1(setup引入computed): {{ message }}</h2>
<h2>方法2.2(setup解构): {{ aMessage }}</h2>
<!-- <h2>1、找到id为2的用户:{{ $store.getters.getFriend1.name }}</h2>-->
<!-- <h2>2、找到id为2的用户:{{ $store.getters.getFriend1ById(2) }}</h2>-->
</div>
</template>
<script>
import {mapGetters} from "vuex";
export default {
computed: {
// 方法1.1
...mapGetters(["doubleCounter"]),
// 方法1.2
...mapGetters({
totalAge: "totalAge",
})
}
}
</script>
<script setup>
import {mapGetters, useStore} from "vuex";
import {computed, toRefs} from "vue";
const store = useStore()
// 方法2.1
const {message: messageFn} = mapGetters(["message"])
const message = computed(messageFn.bind({$store: store}))
// 方法2.2
// const {message: aMessage} = toRefs(store.getters)
// 方法2.3 针对某个getters,属性使computed
const aMessage = computed(() => store.getters.message)
</script>
<style scoped>
</style>
Mutation
Mutation的基本使用
- 更改Vuex的store中的状态的唯一方法是提交mutation:
mutations: {
add(state){
state.counter++
},
changeName(state,newName){
state.name = newName
},
incrementLevel(state){
state.level++
},
[CHANGE_INFO](state,newInfo){
state.name = newInfo.name
state.level = newInfo.level
}
},
<template>
<div class="app">
<button @click="changeName">修改name</button>
<h2>name:{{$store.state.name}}</h2>
<button @click="incrementLevel">level递增</button>
<h2>level:{{$store.state.level}}</h2>
<p>传参</p>
<button @click="changeInfo">commit</button>
</div>
</template>
<script>
import { CHANGE_INFO } from "@/store/mutation_types"
export default {
name: "05",
computed:{
},
methods:{
changeName(){
//不规范
// this.$store.state.name = "yuyyu"
//标准
this.$store.commit("changeName","小鱼")
},
incrementLevel(){
this.$store.commit("incrementLevel")
},
changeInfo(){
this.$store.commit("CHANGE_INFO", {
name:"呵呵姑娘",
level:123
})
}
}
}
</script>
//mutation_types.js
export const CHANGE_INFO = "CHANGE_INFO"
Mutation常量类型(关于设计规范)
定义常量:
//mutation_types.js
export const CHANGE_INFO = "CHANGE_INFO"
定义Mutation:
[CHANGE_INFO](state,newInfo){
state.name = newInfo.name
state.level = newInfo.level
}
提交Mutation:
changeInfo(){
this.$store.commit("CHANGE_INFO", {
name:"呵呵姑娘",
level:123
})
}
mapMutations
<template>
<div class="app">
<button @click="changeName('修改了')">修改name</button>
<h2>name:{{$store.state.name}}</h2>
<button @click="incrementLevel">level递增</button>
<h2>level:{{$store.state.level}}</h2>
<p>传参</p>
<button @click="changeInfo({name:'呵呵姑娘',level:123 })">commit</button>
</div>
</template>
<script>
import { CHANGE_INFO } from "@/store/mutation_types"
import {mapMutations} from "vuex";
export default {
name: "05",
computed:{
},
methods:{
btnClick(){
console.log("btnClick")
},
// ...mapMutations(["changeName","incrementLevel",CHANGE_INFO])
}
}
</script>
<script setup>
import {mapMutations, useStore} from "vuex";
import { CHANGE_INFO } from "@/store/mutation_types"
// 手动映射和绑定
const mutations = mapMutations(["changeName","incrementLevel",CHANGE_INFO])
const newMutation = {}
const store = useStore()
Object.keys(mutations).forEach(key =>{
console.log(newMutation[key])
newMutation[key] = mutations[key].bind({$store:store})
})
console.log(newMutation)
const {changeName,incrementLevel,changeInfo} = newMutation
</script>
<style scoped>
</style>
-
一条重要的原则就是要记住mutation必须是同步函数
- 这是因为devtool工具会记录mutation的日记;
- 每一条mutation被记录,devtoolsi都需要捕捉到前一状态和后一状态的快照;
- 但是在mutation中执行异步操作,就无法追踪到数据的变化:
-
所以Vuex的重要原则中要求mutation必须是同步函数;
- 但是如果我们希望在Vux中发送网络请求的话需要如何操作呢?
Mutation的重要原则
-
一条重要的原则就是要记住mutation必须是同步函数
-
这是因为devtool工具会记录mutation的日记;
-
每一条mutation被记录,devtoolsi都需要捕捉到前一状态和后一状态的快照;
-
但是在mutation中执行异步操作,就无法追踪到数据的变化;
-
重要原则:不要再mutation方法中执行一步操作
- 所以Vuex的重要原则中要求mutation必须是同步函数;
Action
action的基本使用
-
Action类似于mutation,不同在于:
- 在Action中修改state的值时,需要提交到mutation, 而mutation可以直接变更状态;
- Action可以包含任意异步操作;
-
这里有一个非常重要的参数context:
- context是一个和store:实例均有相同方法和属性的context对象;
- 所以我们可以从其中获取到commit方法来提交一个mutation,或者通过context…state和context.getters来获取state和getters;
-
但是为什么它不是store对象呢?这个等到我们讲Modules时再具体来说;
mutations:{
increment(state){
state.counter++
}
},
actions:{
increment(context){
context.commit("increment")
}
}
action的分发操作
- 如何使用action?进行action的分发:
- 分发使用的是 store 上的dispatch函数;
- 携带参数
- 以对象的形式进行分发
<template>
<div class="home">
<h2>当前计数{{$store.state.counter}}</h2>
<button @click="actionBtnClick">发起action</button>
<p>带参派发</p>
<h2>name:{{$store.state.name}}</h2>
<button @click="nameBtnClick">发起action修改name</button>
<p>以对象的形式进行派发</p>
<h2>name:{{$store.state.name}}</h2>
<h2>level:{{$store.state.level}}</h2>
<button @click="objBtnClick">以对象的形式进行派发</button>
</div>
</template>
<script>
export default {
name: "07_",
methods:{
actionBtnClick(){
this.$store.dispatch("incrementAction") //派发一个action
},
nameBtnClick(){
this.$store.dispatch("changeNameAction","呵呵小子")
},
objBtnClick(){
this.$store.dispatch({
type:"objChangeAction",
name:"老于",
level:159
})
}
}
}
</script>
<script setup>
import {useStore} from "vuex";
// const store = useStore()
// function actionBtnClick(){
// store.dispatch("incrementAction")
// }
</script>
<style scoped>
</style>
actions: {
incrementAction(context){
// console.log(context.commit) //用于提交mutation
// console.log(context.getters) //getters
// console.log(context.state) //state
context.commit("increment")
},
changeNameAction(context,newName){
context.commit("changeName",newName)
},
objChangeAction(context,newObj){
context.commit(CHANGE_INFO,newObj)
}
},
action 的异步操作
-
Action通常是异步的,那么如何知道 action 什么时候结束?
-
我们可以通过action返回Promise,在Promise的then中处理完成后的操作;
-
actions:{ increment(context){ return new Promise((resolve) => { setTimeout(() => { context.commit("increment") resolve("异步操作完成") },1000); }) } }
-
const store = useStore(); const increment = () => { store.dispatch("increment").then(res => { console.log(res,"异步完成") }) }
-
actions: {
// fetchHomeMultidataAction(){
// // 返回promise,给promise设置then
// fetch("http://123.207.32.32:8000/home/multidata").then(res => {
// res.json().then(data => {
// console.log(data)
// })
// })
//
// fetch("http://123.207.32.32:8000/home/multidata").then(res => {
// return res.json()
// }).then(data => {
// console.log(data)
// })
//
// }
async fetchHomeMultidataAction(context){
const res = await fetch("http://123.207.32.32:8000/home/multidata")
const data = await res.json()
console.log(data)
// 修改数据
context.commit("changeBanner",data.data.banner.list)
context.commit("changeRecommends",data.data.recommend.list)
}
},
mutations: {
changeBanner(state,newBanner){
state.banner = newBanner
},
changeRecommends(state,newRecommends){
state.recommend = newRecommends
}
},
Module
module的基本使用
- 什么是Module?
- 由于使用单一状态树,应用的所有状态会集中到一个比较大的对象,当应用变得非常复杂时,sto「对象就有可能变得相当臃肿:
- 为了解决以上问题,Vuex允许我们将store分割成模块(module);
- 每个模块拥有自己的state、mutation、action、getter、甚至是嵌套子模块;
module的局部状态
- 对于模块内部的 mutation 和 getter ,接收的第一个参数是模块的局部状态对象:
const counter = {
state: () => ({
counter:99
}),
mutations: {
increment(state){
state.counter++
},
incrementCount(state){
state.counter++
}
},
getters:{
dCounter(state,getters,rootState) {
return state.counter + rootState.counter
}
},
actions: {
incrementCountAction(context){
context.commit("incrementCount")
}
}
}
export default counter
modules: {
home:homeModule,
counterModule:counterModule
}
<template>
<div class="home">
<h2>Home Page</h2>
<!-- 1.使用state时,是需要state.moduleName.xxx-->
<h2>Counter模块的counter:{{$store.state.counterModule.counter}}</h2>
<!-- 2.使用getters时,是直接getters.xxx-->
<h2>Counter模块的doubleCounter:{{$store.getters.dCounter}}</h2>
<button @click="incrementCounter">count模块+1</button>
</div>
</template>
<script>
export default {
name: "11_"
}
</script>
<script setup>
// 告诉vuex发起网络请求
import {useStore} from "vuex";
const store = useStore()
// 派发事件时,默认也是不需要跟模块的名称
// 提交mutation时,默认也是不需要跟模块的名称
function incrementCounter(){
store.dispatch("incrementCountAction")
}
</script>
<style scoped>
</style>
module的命名空间
- 默认情况下,模块内部的action和mutation仍然是注册在全局的命名空间中的:
- 这样使得多个模块能够对同一个action或mutation作出响应;
- Getter同样也默认注册在全局命名空间;
- 如果我们希望模块具有更高的封装度和复用性,可以添加 namespaced:true 的方式使其成为带命名空间的模块:
- 当模块被注册后,它的所有getter、action及mutation都会自动根据模块注册的路径调整命名;
使用方法:
counterModule.js
const counter = {
namespaced:true, 重要
state: () => ({
counter:99
}),
mutations: {
incrementCount(state){
state.counter++
}
},
getters:{
dCounter(state,getters,rootState) {
return state.counter + rootState.counter
}
},
actions: {
incrementCountAction(context){
context.commit("incrementCount")
}
}
}
<h2>Counter模块的doubleCounter:{{$store.getters["counterModule/dCounter"]}}</h2>
<script setup>
// 告诉vuex发起网络请求
import {useStore} from "vuex";
const store = useStore()
// 派发事件时,默认也是不需要跟模块的名称
// 提交mutation时,默认也是不需要跟模块的名称
function incrementCounter(){
// 有命名空间的情况下
store.dispatch("counterModule/incrementCountAction")
// 没有命名空间的情况下
// store.dispatch("incrementCountAction")
}
</script>