目录
- 1. Vuex 概述
- 1.1 Vuex是什么?
- 1.2 使用Vuex有什么好处?
- 1.3 Vuex中适合存储什么数据?
- 2. Vuex 基本使用
- 2.1 基本使用步骤
- 2.2 Vuex 数据变更:Mutation
- 2.3 Vuex 处理异步任务:Action
- 2.4 Vuex 数据加工处理:Getter
1. Vuex 概述
1.1 Vuex是什么?
Vuex 是实现组件全局状态管理 的一种机制,可以方便的实现组件之间数据的共享。
1.2 使用Vuex有什么好处?
使用Vuex统一管理状态有以下好处:
- 能够在Vuex中集中管理共享的数据,易于开发和后期维护
- 能够高效的实现数据之间的共享,提高开发效率
- 存储在Vuex中的数据时响应式的,能够实时保持数据与页面同步
1.3 Vuex中适合存储什么数据?
一般情况下,只有组件之间共享的数据才会存储在Vuex中,对于组件的私有数据,尽量存储在组件自身的data
中。
2. Vuex 基本使用
2.1 基本使用步骤
1. 安装Vuex依赖
npm install vuex --save
2. 导入Vuex
import Vuex from 'vuex'
Vue.use(Vuex)
3. 创建store对象
const store = new Vuex.Store({
//state中存放共享的数据
state:{
count:1
}
})
4. 将store对象挂载到vue实例中
new Vue ({
el:'#app',
render:h=>h(app),
store
})
5. 访问state中数据
第一种方式:
this.$store.state.数据名称
第二种方式:
//1.从Vuex中按需导入mapState函数
import {mapState} from 'vuex'
//2.将全局数据映射为当前组件的计算属性
computed: {
...mapState(['count'])
}
//3.然后直接使用数据即可
<div>
<p>{{count}}</p>
</div>
2.2 Vuex 数据变更:Mutation
Mutation
用于变更state中的数据。
只能通过mutation
来变更Store
中的数据,不可以直接操作Store
中的数据,这样可以集中监控所有数据的变化
注意:mutation
中不能执行异步操作
1. 定义mutation,数据进行变更
const store = new Vuex.Store({
state:{
count:1
},
mutations:{
//第二个参数为传递进来的参数
add(state,num){
state.mount += num
}
}
})
2. 触发mutation,使用数据变更方法
(1)第一种触发方式:
methods:{
handle(){
// commit的作用就是调用某个mutation函数
this.$store.commit('add',5) // 5为携带的参数
}
}
//也可以直接调用
<div>
<button @click="$store.commit('add',5) ">+5</button>
</div>
(2)第二种触发方式:
//1.从Vuex中按需导入mapMutations函数
import {mapMutations} from 'vuex'
//2.将指定的mutations函数映射为当前组件的methods方法
methods: {
...mapMutations(['add'])
}
//3.然后直接调用该函数即可
<div>
<button @click="add(5)">+5</button>
</div>
2.3 Vuex 处理异步任务:Action
如果我们需要通过异步操作来对数据进行变更,不能使用mutation
,而是要在Action
中定义异步任务。但是在Action
中依旧是通过触发mutation
来进行数据的变更操作。
注意:在Action
中不能修改state
中的数据,必须要通过context.commit()
触发某个mutation
函数来修改数据。
1. 定义Action,定义异步任务
const store = new Vuex.Store({
state:{
count:1
},
mutations:{
add(state,num){
state.mount += num
}
},
actions:{
addAsync(context,num){
setTimeout(() =>{
context.commit('add',num)
},2000)
}
}
})
2. 触发Action,调用异步任务
(1)第一种调用方式:
methods:{
handle(){
// dispatch的作用就是触发某个Action异步任务
this.$store.dispatch('addAsync',5)
}
}
(2)第二种调用方式:
//1.从Vuex中按需导入mapActions函数
import {mapActions} from 'vuex'
//2.将指定的Action函数映射为当前组件的methods方法
methods: {
...mapActions(['addAsync'])
}
//3.然后直接调用该异步任务即可
<div>
<button @click="addAsync(5)">+5</button>
</div>
2.4 Vuex 数据加工处理:Getter
Getter
用于对state
中数据进行加工处理形成新的数据,这个过程不会改变原有的数据,而是产生一个数据的副本。
-
Getter
可以Store
中已有数据进行加工处理形成新的数据,类似于vue中的计算属性。 -
Store
中的数据发生变化,Getter
中的数据也会随之发生改变。
1. 定义Getter,数据进行加工处理
const store = new Vuex.Store({
state:{
count:1
},
getters:{
showNum: (state) =>{
return count*2
}
}
})
2. 使用Getter
(1)第一种使用方式:
注意:如果在模板中使用,不要写this
,写成$store.getters.showNum
即可。
this.$store.getters.showNum
(2)第二种使用方式:
//1.从Vuex中按需导入mapGetters函数
import {mapGetters} from 'vuex'
//2.将mapGetters映射为当前组件的计算属性
computed: {
...mapGetters(['showNum'])
}
//3.然后直接使用即可
<div>
<p>{{showNum}}</p>
</div>