目录
什么是Vuex?
官方文档中给出的解释:
Vuex 是一个专为 Vue.js 应用程序开发的状态管理模式。它采用集中式存储管理应用的所有组件的状态,并以相应的规则保证状态以一种可预测的方式发生变化。
简单来说,Vuex就是一个状态机,采用集中式存储帮助我们管理所有组件的共享状态,可以用来解决多组件数据通信,可以把vuex理解成一个仓库,假设有A、B两个组件需要通信传值,那么可以把A组件和B组件的数据放到Vuex中, A组件想要获取B组件数据从vuex中拿 B组件想要获取A组件的数据从Vuex拿。
Store
每一个 Vuex 应用的核心就是 store(仓库)。“store”基本上就是一个容器,它包含着你的应用中大部分的状态 (state)。
在项目中安装和配置 Vuex
整体步骤:
-
安装。
npm install vuex@3.6.2
开发依赖 : npm i xxxx --save-dev ; npm i xxxx -D ;
生产依赖: npm i xxxx --save ; npm i xxxx -S; npm i xxxx
-
实例化stroe
与router一样,当我们在项目中使用vuex之后,为了方便代码维护,我们一般需要做特殊的目录调整,约定的结构如下:
根组件
└── src
├── main.js
├── router
│ └── index.js # 路由
└── store
└── index.js # vuex
在store/index.js 中放置具体的代码,具体如下:
import Vue from 'vue'
import Vuex from 'vuex'
Vue.use(Vuex)
const store = new Vuex.Store({
state(){
return {
// 就是公共的数据,所有的组件都可以直接使用
count: 100
}
}
})
export default store
3、向Vue实例注入store
在src/main.js中:
- 导入store并将其注入Vue实例
// 省略其他
// 1. 导入store
import store from './store'
new Vue({
// 省略其他...
store // 2. 注入Vue实例
})
4、在组件中使用store
在任意组件中,通过this.$store.state
来获取公共数据 。
Vuex中的五个核心状态
- State
- Getters
- Mutations
- Actions
- Modules
------------------------------------------------------------------------------------------------------------------------
State:在`State`中存放状态,可将状态理解为组件中的`data`,只不过在`state`中一般存放的是组件共享的数据,而在组件内的`data`中一般存放组件的私有数据。
------------------------------------------------------------------------------------------------------------------------
Getters:有时候我们需要从 store 中的 state 中派生出一些状态,例如对列表进行过滤并计数:
Vuex 允许我们在 store 中定义“getter”(可以认为是 store 的计算属性)。就像计算属性一样,getter 的返回值会根据它的依赖被缓存起来,且只有当它的依赖值发生了改变才会被重新计算。
Getter 接受 state 作为其第一个参数:
------------------------------------------------------------------------------------------------------------------------
mutations: --突变 ,唯一修改state数据的一种方式--实际上就是用来修改state数据的,只能执行同操作。
------------------------------------------------------------------------------------------------------------------------
actions:通过commit去触发mutations,提交突变,可以处理同步或异步任务
------------------------------------------------------------------------------------------------------------------------
moduels:将 store 分割成模块(module)。每个模块拥有自己的 state、mutation、action、getter、甚至是嵌套子模块
------------------------------------------------------------------------------------------------------------------------
实例:
// js代码
<script>
// 仓库配置对象
let storeConf={
state:{
storeMsg:'仓库里的msg数据'
},
getters:{
storeMsgUpper(state){ //第一个参数是默认参数
return state.storeMsg.toUpperCase()
}
},
mutations:{
// 突变 修改state中的数据 payload提交突变时候传递的数据 第一个参数是默认参数
changeMsg(state,payload){
state.storeMsg=payload
}
},
actions:{
// 分发动作 sto类似于仓库对象的对象 第一个参数是默认参数
getMsg( {commit,dispatch,mutations,actions},payload){
// console.log(sto,payload)
commit('changeMsg',payload)
}
}
}
//2.生成一个仓库
let store=new Vuex.Store(storeConf)
new Vue({
el:"#app",
// 注册仓库
store,
data:{
msg:'我是父组件'
},
created(){
console.log(this.$store.state)
console.log(this.$store.getters)
// console.log(this.$store.mutations)
// console.log(this.$store.actions)
}
})
</script>
// html代码
<div id="app">
{{msg}}
<br>
{{$store.state.storeMsg}}--------
{{$store.getters.storeMsgUpper}}
<button @click='$store.commit("changeMsg","test")'>提交突变</button>
<button @click='$store.dispatch("getMsg","terry")'>分发动作</button>
</div>
Vuex的辅助函数
通常使用state,或者mutation都需要this.store.state或者this.store.commit来使用,但是有时候调用太多的状态,这样使用还是有些麻烦,所以可以借助vuex的辅助函数来解决这个问题。
通过辅助函数mapState、mapGetters、mapActions、mapMutations,把vuex.store中的属性映射到vue实例身上,这样在vue实例中就能访问vuex.store中的属性了。
使用时需要在组建内引入:
import {mapState,mapMutations,mapActions,mapGetters} from "vuex"
在组建中引用:
- Vuex中的state和getters需要引入到computed中
- Vuex中的mutations和actions需要引入到methods中
引入之后直接调用就可以了
可以是对象也可以是数组 数据['名'] 对象{属性:'名'}
实例:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
<script src="https://cdn.jsdelivr.net/npm/vue@2.7.10"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/vuex/3.6.0/vuex.min.js" integrity="sha512-uN93RUcJ9frHH6dyLknjgalFe7JNkfb3OjW4Qgg5xjaVA3U7l0diZ3hGL2Puk/38sp7xD/SLHdNFit7Kq3RbtQ==" crossorigin="anonymous" referrerpolicy="no-referrer"></script>
</head>
<body>
<div id="app">
{{msg}}
{{MSG}}
<button @click="set('lerry')">提交突变</button>
<button @click="loadData('terry')">分发动作</button>
</div>
<script>
console.log(Vuex,'状态机对象');
let {mapState,mapGetters,mapActions,mapMutations} = Vuex;
// 声明状态机
let store=new Vuex.Store(
{
state:{
msg:"hello world",
msg1:"hello",
msg2:"hello",
},//维护公共状态 类似于data
getters:{
MSG(state){//默认参数 就是state
return state.msg.toUpperCase()
}
},//类似于计算属性 将state数据处理后返回
// 突变 唯一修改state的方式 同步操作
mutations:{
// 默认参数 state 修改state
set(state,payload){
state.msg=payload;
}
},
// 动作 异步操作 获取后台响应 提交数据给突变
actions:{
// sto默认参数 类状态机对象
// payload 是触发动作传递的参数
// sto {commit,dispatch,state,getters}
loadData(sto,payload){
let res = '123456789';
console.log(sto,payload);
sto.commit('set',payload)
}
},
modules:{
}
}
)
// 注入vue实例
new Vue({
store,
el:"#app",
data:{
},
computed: {
// 引入辅助函数mapState和mapGetters
...mapState(['msg','msg1','msg2']),
...mapGetters(['MSG'])
},
methods:{
// 引入辅助函数mapActions和mapMutations
...mapActions(['loadData']),
...mapMutations(['set']),
}
})
</script>
</body>
</html>