Vuex-状态管理

147 阅读4分钟
  • 每一个Vuex应用的核心就是store(仓库)
    • store本质上是一个容器,它包含着你的应用中大部分的状态
  • Vuex 和单纯的全局对象有什么区别呢?
  • 第一: Vuex的状态存储是响应式的
    • 当Vue组件从store中读取状态的时候,若store中的状态发生变化,那么相应的组件也会被更新
  • 第二:你不能直接改变store中的状态
    • 改变store中的状态的唯一途径就是显示提交(commit)mutation
    • 这样使得我们可以方便的跟踪每一个状态的变化,从而让我们能够通过一些工具帮助我们更好的管理应用的状态
  • 使用步骤
    • 创建Store对象;
    • 在app中通过插件安装
  • 组件中使用的store,按照如下方式
    • 在模板中使用
    • 在options api中使用,比如computed
    • 在setup中使用

单一状态树

  • Vuex 使用单一状态树
    • 用一个对象就包含了全部的应用层级的状态
    • 采用的是SSOT,Single Source of Truth, 也可以翻译成当以数据源
  • 这也就意味着,每个应用将仅仅包含一个store案例
    • 单状态树和模块化并不冲突,后面会说到module的概念
  • 单一状态树的优势:
    • 如果你的状态信息是保存多个Store对象中,那么之后的管理和维护等等都会变得特别困难
    • 所以Vuex也使用了单一状态树来管理应用层级的全部状态
    • 单一状态树能够让我们最直接的方式找到某个状态的片段
    • 而且在之后的维护和调试过程中,也可以非常方便的管理和维护

组件获取状态

  • 使用计算属性
        computed: {
            counter() {
                return this.$store.state.counter
            }
        }
    
  • 但是,如果有很多个状态都需要获取的话,可以使用mapState的辅助函数:
    • mapState的方式一:对象类型
    • mapState的方式二:数组类型
    • 也可以使用展开运算符和原来有的computed混合在一起
  • 在setup中使用mapState
    • 通过useStore拿到store后去获取某个状态即可
    • 但是如果我们需要使用mapState的功能呢?
  • 默认情况下,Vuex并没有提供非常方便的使用mapState的方式,这里我们进行了一个函数封装
import { useStore, mapState } from 'vuex';
import { computed } from 'vue'
export function useState(mapper) {
    const store = useStore();
    const stateFns = mapState(mapper)
    const state = {}
    Object.keys(stateFns).forEach(fnKey => {
        state[fnKey] = computed(stateFns[fnKey].bind({$store:store}))
    })
    
    retrun state
}
setup() {
    const state = useState({
        name: state => state.name,
        age: state => state.age,
        height: state => state.hegiht
    })
    
    return {
        ...state
    }
}

getters的基本使用

  • 某些属性我们可能需要经过变化后来使用,这个时候可以使用getters
const store = createStore({
    state() {
        return {
            counter: 0,
            name: "coderwhy",
            age: 18,
            height: 1.88
            books: [
                {name: "vue.js", count:2, price: 110},
                {name: "react", count:3, price: 120},
                {name: "webpack", count:4, price: 123},
            ]
        }
    },
    getters: [
        totalPrice(state) {
            let totalPrice = 0;
            for (const book of state.books) {
                totalPrice += book.count * book.price
            }
            return totalPrice
        }
    ]
})
<div>
    <h2>{{ $store.getters.totalPrice }}</h2>
</div>
  • getters可以接受第二个参数
getters: {
    totalPrice(state, getters) {
        let totalPrice = 0
        for (const book of state.books) {
            totalPrice += book.count * book.price
        }
        
        return totalPrice + ", " + getters.myName
    },
    myName(state) {
        return state.name
    }
}

getters的返回函数

  • getters中的函数本身,可以返回一个函数,那么在使用的地方相当于可以调用这个函数
    getters: {
        totalPrice(state) {
            return (price) => {
               let totalPrice = 0
               for (const book of state.books) {
                   if (book.price < price) continue
                   totalPrice += book.count * book.price
               }
               
               return totalPrice
            }
        }
    }

mapGetters的辅助函数

  • 这里我们也可以使用mapGetters的辅助函数
computed: {
    ...mapGetters(["totalPrice", "myName"]),
    ...mapGetters([        finalPrice: "totalPrice",        finalName: "myName",    ])

}

-在setup中使用

import { useStore, mapGetters } from 'vuex'
import { computed } from 'vue'

export function useGetters(mapper) {
    const store = useStore()
    const stateFns = mapGetters(mapper)
    const state = {}
    Object.keys(stateFns).forEach(FnKey => {
        state[fnKey] = computed(stateFns[fnKey].bind({$store: store}))
    })
}

Mutation基本使用

  • 更改Vuex的store中的状态的唯一方法是提交mutation
mutations: {
    increment(state) {
        state.counter++
    },
    decrement(state) {
        state.counter--
    }
}

Mutatio携带的数据

  • 很多时候我们在提交mutation的时候,会携带一些数据,这个时候我们可以使用参数
mutations: {
    addNumber(state, payload) {
        state.counter += payload
    }
}
  • payload为对象类型
addNumber(state, payload) {
    state.counter += payload.count
}
  • 对象风格的提交方式
$store.commit({
    type: "addNumber",
    count: 100
})

Mutation 常量类型

  • 定义常量:mutation-type.js
export const ADD_NUMBER = 'ADD_NUMBER'
  • 定义mutation
[ADD_NUMBER](state, payload) {
    state.counter += payload.count
}
  • 提交mutation
$store.commit({
    type: ADD_NUMBER,
    count: 100
})

mapMutations辅助函数

  • 可以借助于辅助函数,帮助我们快速映射到对应的方法中
methods: {
    ...mapMutations({
        addNumber: ADD_NUMBER
    }),
    ...mapMutations(["increment", "decrement"]),
}
  • 在setup中使用也是一样的:
const mutations = mapMutations(['increment', 'decrement'])
const mutations2 = mapMutations({
    addNumber: ADD_NUMBER
})

mutation重要原则

  • 一条重要的原则就是要记住mutation必须是同步函数
    • 这是因为devtool工具会记录mutation日记
    • 每一条mutation被记录,devtools都需要捕捉到前一状态和后一状态的快照
    • 但是在mutation中执行异步操作,就无法追踪到数据的变化
  • 所以Vuex的重要原则中要求mutation必须是同步函数
    • 但是如果我们希望在Vuex中发送网络请求的话需要如何操作呢?

actions 的基本使用

  • Action类似于mutation,不同在于:
    • Action提交的是mutation,而不是直接变更状态
    • Action可以包含任意异步操作
  • 这里有一个非常重要的参数context:
    • context是一个和store实列均有相同的方法和属性context对象
    • 所以可以从中获取commit方法来提交一个mutation,或者通过context.state和context.getters来获取state和getters

actions的分发操作

  • 如何使用action呢?进行action分发
    • 分发使用的是store上的dispatch函数
    add() {
        this.$store.diapatch("increment");
    }
    
  • 同样的,它也可以携带我们的参数
    add() {
        this.$store.dispatch("increment", {count: 100})
    }
    
  • 也可以以对象的形式进行分发
    add() {
        this.$store.dispatch({
            type: "increment",
            count: 100,
        })
    }
    
  • action也有对应的辅助函数
    • 对象类型的写法
    • 数组类型的写法
    methods: {
        ...mapActions(["increment", "decrement"]),
        ...mapActions({
            add: "increment",
            sub: "decrement"
        })
    },
    const actions1 = mapActions(["decrement"]);
    const actions2 = mapActions({
        add: "increment",
        sub: "decrement"
    })
    
  • 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, "异步完成")
    
    })

}

module的基本使用

  • 什么是Module
    • 由于使用单一状态树,应用的所有状态会集中到一个比较大的对象,当应用变得非常复杂时,store对象就有可能变得相当臃肿
    • 为了解决以上问题,Vuex允许我们将store分割成模块
    • 每个模块拥有自己的state、mutation、action、getter、甚至是嵌套子模块
    const moduleA = {
        state: () => ({}),
        mutations: {},
        actions: {},
        getters: {}
    }
    
    const moduleB = {
        state: () => ({}),
        mutations: {},
        actions: {}
    }
    
    const store = createStore({
        modules: {
            a: moduleA,
            b: moduleB
        }
    })
    
    store.state.a //moduleA 的状态
    store.state.b // moduleB 的状态
    

module的局部状态

  • 对于模块内部的mutation和getter,接收的第一个参数是模块的局部状态对象
mutations: {
    changeName(state) {
        state.name = "coderwhy"
    }
},
getters: {
    info(state, getters, rootState) {
        return `name: ${state.name}`
    }
}
actions: {
   changeNameAction({state, commit, rootState}) {
       commit("changeName", "kobe")
   }
}

module的命名空间

  • 默认情况下,模块内部的action和mutation仍能是注册在全局的命名空间中的
    • 这样使得多个模块能够对同一个action或mutation作出响应
    • Getter同样也默认注册在全局命名空间;
  • 如果我们希望模块具有更高的封装度和复用性,可以添加namespaced:true的方式使其成为带命名空间的模块
    • 当模块被注册后,它的所有getter、action及mutation都会自动根据模块注册的路径调整命名;
namespaced: true,
state() {
    return {
        name: "why",
        age: 18,
        height: 1.88
    }
},
mutations: {
    changeName(state) {
        state.name = "coderwhy"
    }
}
getters: {
    info(state, getters, rootState, rootGetters) {
        return `name:${state.name} age:${state.age} height:${state.height}`
    }
},
actions: {
    changeNameAction({commit, dispatch, state, rootState, getters, rootGetters}){
       commit("changeName", "kobe")
    }
}

module修改或派发根组件

  • 如果我们希望在action中修改root中的state,那么有如下的方式:
changeNameAction({commit, dispatch, state, rootState, getters, rootGetters}) {
    commit("changeName", "kobe");
    commit("changeRootName", null, {root: true});
    dispatch("changeRootNameAction", null, {root: true})
}