Vuex的概述
Vuex是什么
Vuex是实现组件全局状态(数据)管理的一种机制,可以方便的实现组件之间数据的共享。
image.png
Vuex的好处
- 能集中管理共享的数据,易于开发和后期维护
- 能高效地实现组件之间的数据共享,提高开发效率
- vuex中的数据是响应式的,能实时保持数据与页面的同步
适用场景
只有组件间共享的数据,才有必要存储到vux中;组件的私有数据存储在自身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的核心概念
个人理解
image.png
State
State提供唯一的公共数据源,所有共享的数据都要统一放到Store的State中进行存储。
const store = new Vuex.store({
state: { count: 0 }
})
访问State
第一种方式
this.$store.state.全局数据名称
第二种方式
// 1.从vuex中导入 mapState 函数
import { mapState } from 'vuex'
// 2.将需要的全局数据映射为当前组件的 computed 计算属性
computed: {
...mapState(['count'])
//把 state 里的数据当成组件数据使用
}
Mutation
Mutation用于变更Store中的数据
- 只能通过mutation变更Store数据,不可以直接操作Store中的数据
- 通过这种方式虽然操作繁琐,但是可以集中监控所有数据的变化
const store = new Vuex.store({
state: { count: 0 },
mutations: {
add(state) {
// 变更状态
state.count ++
}
}
})
触发Mutation(commit)
第一种方式
this.$store.commit('add')
第二种方式
// 1.从vuex中导入 mapMutations 函数
import { mapMutations} from 'vuex'
// 2.将指定的 mutations 函数映射为当前组件的 methods 函数
methods: {
...mapMutations(['add','addN'])
//把 mutations 里的函数当成组件函数使用
}
Action
Action用于处理异步任务
如果通过异步操作更改数据,必须通过Action,而不能直接用Mutation;是在Action中触发Mutation间接更改。
const store = new Vuex.store({
state: { count: 0 },
mutations: {
...
},
actions: {
addAsync(context) {
setTimeOut(() => {
context.commit('add')
},1000)
}
}
})
触发Action(dispatch)
第一种方式
this.$store.dispatch('addAsync')
第二种方式
// 1.从vuex中导入 mapActions 函数
import { mapActions } from 'vuex'
// 2.将指定的 actions 函数映射为当前组件的 methods 函数
methods: {
...mapActions(['addAsync','addNAsync'])
//把 actions 里的函数当成组件函数使用
}
Getter
Getter用于对Store中的数据进行加工处理形成新的数据。
- Getter可以对Store中已有的数据加工处理之后形成新的数据,类似Vue的计算属性。
- Store中数据发生变化,Getter的数据也会跟着变化。
const store = new Vuex.store({
state: { count: 0 },
mutations: {
...
},
actions: {
...
},
getters: {
showNum: state => {
return '数量是:' + state.count
}
}
})
使用Getter
第一种方式
this.$store.getters.名称
第二种方式
import { mapGetters } from 'vuex'
computed: {
...mapGetters(['showNum'])
//把 getters 里的数据当成组件数据使用
}