Vuex的概念
-
什么是Vuex?
Vuex是实现组件全局状态(数据)管理的一种机制,可以方便的实现组件之间的数据共享,通俗说就是方便组件间的数据管理和分享,同时安全性、效率都比较高。
-
原来的组件间的数据传递
原来的父传子,子传父使数据传递步骤变得复杂,传递过程经过组件与组件间也变得十分的不安全。 -
使用Vuex的优点?
1.能够在vuex中集中管理共享的数据,便于开发和后期进行维护
2.能够高效的实现组件之间的数据共享,提高开发效率
3.存储在vuex中的数据是响应式的,当数据发生改变时,页面中的数据也会同步更新(重点应用) Vuex的数据共享实现了数据的双向绑定,可以实时更新数据。 -
应用
一般来说,vuex中会放入组件中的共享的、公共的数据。但是需要按照实际项目的情况去考量。
Vuex的四大核心属性
State
- state属性中统一存放着公共的数据
const store = new Vuex.Store({
state: { count: 0 }
})
组件访问state中数据的两种方式:
第一种
this.$store.state.全局数据名称
第二种
// 1. 从 vuex 中按需导入 mapState 函数
import { mapState } from 'vuex';
//通过刚才导入的 mapState 函数,将当前组件需要的全局数据,映射为当前组件的 computed 计算属性:
computed: {
...mapState(['count'])
}
<!-- 直接可以使用共享数据的count -->
<h3>{{count}}</h3>
Mutation
Mutation用于更改Store中的数据。
优点:可以集中的监听所有数据的变化。
// 定义 Mutation
const store = new Vuex.Store({
state: {
count: 0
},
mutations: {
add(state) {
// 变更状态
state.count++
}
}
})
组件中修改公共数据State里的两种方式:
第一种
this.$store.commit('add')//add为mutations中定义的方法
<button @click="Add">+1</button>
methods:{
Add(){
//使用commit函数调用mutations中的对应函数,
//第一个参数就是我们要调用的mutations中的函数名
//第二个参数就是传递给add函数的参数
this.$store.commit('add',10)
}
}
注意:若是传递的参数有多个,根据官方文档,最好是传递一个包含多个参数的对象。
// ...
mutations: {
increment (state, payload) {
//payload是一个对象包含组件传递过来的参数
state.count += payload.amount
}
}
第二种
import { mapMutations } from 'vuex'
//通过刚才导入的 mapMutations 函数,将需要的 mutations 函数,映射为当前组件的 methods 方法:
// 2. 将指定的 mutations 函数,映射为当前组件的 methods 函数
methods: {
...mapMutations(['add', 'addN','sub'])
}
通过映射定义的方法可以直接在模板上调用:
<button @click="add(10)">+1</button>
<button @click="sub(5)">-1</button>
Action
Action用于处理异步任务,vuex中通过Action分发处理异步请求,Mutation中则用于做同步的处理,但是修改数据还是需要通过触发Mutation中的方法间接改变数据。
触发actions的两种方式:
第一种
this.$store.dispatch('addAsync')
// 定义 Action
const store = new Vuex.Store({
// ...省略其他代码
mutations: {
add(state) {
state.count++
}
},
actions: {
addAsync(context) {
setTimeout(() => {
//context可以看作是store实例
context.commit('add')
}, 1000)
}
}
})
// 触发 Action
methods: {
handle() {
// 触发 actions 的第一种方式
this.$store.dispatch('addAsync')
}
}
触发异步任务函数时可传递参数:
// 定义 Action
const store = new Vuex.Store({
// ...省略其他代码
mutations: {
addN(state, step) {
state.count += step
}
},
actions: {
addNAsync(context, step) {
setTimeout(() => {
context.commit('addN', step)
}, 1000)
}
}
})
第二种
// 1. 从 vuex 中按需导入 mapActions 函数
import { mapActions } from 'vuex'
//通过刚才导入的 mapActions 函数,将需要的 actions 函数,映射为当前组件的 methods 方法:
// 2. 将指定的 actions 函数,映射为当前组件的 methods 函数
methods: {
...mapActions(['addASync', 'addNASync'])
}
Getter
Getter 用于对 Store 中的数据进行加工处理形成新的数据。
Getter的特性:
① Getter 可以对 Store 中已有的数据加工处理之后形成新的数据,类似 Vue 的计算属性。
② Store 中数据发生变化,Getter 的数据也会跟着变化。
使用getters的两种方式:
第一种
this.$store.getters.名称
// 定义 Getter
const store = new Vuex.Store({
state: {
count: 0
},
getters: {
showCount: state => {
return '当前最新的数量是【'+ state.count +'】'
}
}
})
第二种
import { mapGetters } from 'vuex'
computed: {
...mapGetters(['showNum'])
}
这种方式可以直接在模板上使用数据。
<h3>{{showCount}}</h3>