Vuex 是一个专为 Vue.js 应用程序开发的状态管理模式。它采用集中式存储管理应用的所有组件的状态,并以相应的规则保证状态以一种可预测的方式发生变化。
五大核心
state、mutations、actions、getters、modules
state
//state中声明状态count,初始值为100 state: { count: 100, },
组件中使用state值
1、在计算属性中直接通过this.$store.state.XXX来获取
//计算属性中获取state值 <template> <div> {{ this.HomeCount }} // 100 </div> </template> <script> export default { computed: { HomeCount() { return this.$store.state.count; }, }, }; </script>
2、利用mapState函数来获取state的值
<template> <div> {{ this.count }} // 100 </div> </template> <script> import { mapState } from "vuex"; export default { computed: { ...mapState(["count"]), }, }; </script>
mutations
如果想要去更新state中的值,就必须要使用mutations去修改。
错误写法: this.$store.state.XXX = XXX
1、定义mutations中修改state值的函数
mutations: { // 注意:mutations中形参只有两个,固定的state和val 如果要传递多个参数,val可以 以对象形式传递 addCount(state, val) { //通过state可以拿到state中的值 val为传递的参数 state.count += val; }, },
2、在组件函数中使用this.$store.commit('触发函数',传递的值)
<template> <div> {{ this.count }} <button @click="addCount">count+1</button> </div> </template> <script> import { mapState } from "vuex"; export default { computed: { ...mapState(["count"]), }, methods: { addCount() { this.$store.commit("addCount", 1); }, }, }; </script>
actions
异步更新state中的值
1、定义actions中的函数,通过形参content.commit去调用mutations中的函数。
mutations: { addCount(state, val) { state.count += val; }, }, actions: { addCountDelay(content) { setTimeout(() => { content.commit("addCount", 1); }, 1000); }, },
2、组件中使用this.$store.dispatch('actions中的函数名')去修改state值
<template> <div> {{ this.count }} <button @click="addCountDelay">count异步+1</button> </div> </template> <script> import { mapState } from "vuex"; export default { computed: { ...mapState(["count"]), }, methods: { addCountDelay() { this.$store.dispatch("addCountDelay"); }, }, }; </script>
getters
1、在getters中定义函数,通过形参state可以对state进行某些操作
getters: { helloCount(state) { return `hello${state.count}`; }, },
获取通过getters操作的值
1、通过mapGetters辅助函数来获取值
<template> <div> {{ this.helloCount }} </div> </template> <script> import { mapGetters } from "vuex"; export default { computed: { ...mapGetters(["helloCount"]), }, }; </script>
2、通过this.$store.getters.XXX
<template> <div> {{ this.helloCount }} </div> </template> <script> export default { computed: { helloCount() { return this.$store.getters.helloCount; }, }, }; </script>
还没有评论,来说两句吧...