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