Vuex学习
Vuex概述
组件之间共享数据的方式
父向子传值:v-bind属性绑定
子向父传值:v-on
兄弟之间组件共享数据:EventBus
$on 接收数据的那个组件
$emit 发送数据的那个组件
Vuex是什么?
Vuex是实现组件全局状态(数据)管理的一种机制,可以方便的实现组件之间数据的共享。
使用Vuex统一管理状态的好处
- 能够在Vuex中集中管理共享的数据,已于开发和后期维护
- 能够高效的实现组件之间的数据共享,提高开发效率
- 存储在vuex中的数据都是响应式的,能够实时保持数据与页面的同步
什么样的数据适合存储到Vuex中
一般情况下,只有组件之间共享的数据,才有必要存储到vuex中;对于组件中的私有数据,依旧存储在自身的data中即可。
Vuex的基本使用
-
安装vuex依赖包
npm install vuex --save
-
导入vuex包
import Vuex from 'vuex' Vue.use(Vuex)
-
创建store对象
const store = new Vuex.Store({ //state 中存放的就是全局共享的数据 state: { count: 0 } })
-
将store对象挂载到vue实例中
new Vue({ el: '#app', render: h => h(app), router, //将创建的共享数据对象,挂载到Vue实例中 //将所有的组件,就可以直接从store中获取全局的数据了 store })
核心概念概述
Vuex中的主要核心概念如下:
State
State提供唯一的公共数据源,所有共享的数据都要统一放到Store的State中进行存储。
// 创建store数据源,提供唯一公共数据
const store = new Vuex.Store({
//state 中存放的就是全局共享的数据
state: { count: 0 }
})
组件访问State的数据的第一种方式:
this.$store.state.全局数据名称 //template中的this可以省略
组件访问State的数据的第二种方式:
// 1.从vuex中按需导入mapState函数
import { mapState } from 'vuex'
// 2.通过刚才导入的mapState函数,将当前组件需要的全局数据,映射为当前组件的computed计算属性
//将全局数据,映射为当前组件的计算属性
computed: {
...mapState(['全局数据名称'])
}
Mutation
Mutation用于变更Store中的数据。(方便后期维护)
- 只能通过Mutation变更Store数据,不可以直接操作Store中的数据。
- 通过这种方式虽然操作起来稍微繁琐一些,但是可以集中监控所有数据的变化
Action
Action专门用于处理异步任务。异步任务如:
setTimeout(()=>{
state.count++
},1000)
如果通过异步操作变更数据,必须通过Action,而不能使用Mutation,但是在Action中还是要通过Mutation的方式间接变更数据,只有mutations中定义的函数,才有权力修改state中的数据。
触发actions异步任务
// 方式一: this.$store.dispatch()
// methods中
addNumAysnc () {
// 在调用dispatch函数触发actions
this.$store.dispatch('addAsync')
}
// store中的actions
actions: {
addAsync (context) {
setTimeout(() => {
// 在actions中不能直接修改state中的数据,必须通过context.commit触发某个mutation才行
context.commit('add')
}, 1000)
}
}
// 方式二: 通过映射
methods: {
...mapActions(['reduceAsync', 'reduceNAsync'])
reduceNumAsync () {
this.reduceAsync()
}
}
// actions中和上面相同
触发actions异步任务时传递参数
// 方式一: this.$store.dispatch()
// methods中
addNAysnc () {
this.$store.dispatch('addNAsync', 2)
}
// store中的actions中
addNAsync (context, N) {
setTimeout(() => {
context.commit('addN', N)
}, 1000)
}
// 方式二: 通过映射
methods: {
...mapActions(['reduceAsync', 'reduceNAsync'])
reduceNuAsync () {
this.reduceNAsync(3)
}
}
// actions中和上面相同
Getter
Getter用于对Store中的数据进行加工处理形成新的数据。
Store中数据发生变化,Getter的数据也会跟着变化。
// 定义 Getter
const store = new Vuex.Store({
state: {
count: 0
},
getters: {
showNum: state => {
return '当前最新的数量是【'+state.count +'】'
}
}
})
使用getter的第一种方式
this.$store.getters.名称
<h3>{{$store.getters.showNum}}</h3>
使用getter的第二种方式
import { mapState, mapMutations, mapActions, mapGetters } from 'vuex'
//通过映射
<h3>{{showNum()}}</h3>
this.$store.getters.名称
<h3>{{$store.getters.showNum}}</h3>
使用getter的第二种方式
import { mapState, mapMutations, mapActions, mapGetters } from 'vuex'
//通过映射
<h3>{{showNum()}}</h3>