Vuex 是什么?
Vuex是实现组件全局状态(数据)管理的一种机制,可以方便的实现组件之间数据的共享。
- 能够在 vuex 中集中管理共享的数据,易于开发和后期维护
- 能够高效地实现组件之间的数据共享,提高开发效率
- 存储在 vuex 中的数据都是响应式的,能够实时保持数据与页面的同步
使用Vuex
安装 vuex 依赖包
npm install vuex --save
导入 vuex 包
import Vuex from 'vuex'
Vue.use(Vuex)
创建 store 对象
const store=new Vuex.Store({
//state中存放的就是全局共享的数据
state:{ count:xxx }
})
将store对象挂载到vue的实例中
new Vue({
el:'#app',
render:h=>h(app),
router,
//将创建的共享数据对象,挂载到Vue实例中
//所有的组件,就可以直接从store中获取全局的数据了
store
})
Vuex 中的主要核心概念
- State
- Mutation
- Action
- Getter
- Module(暂不介绍)
① State:提供唯一的公共数据源,所有共享的数据都要统一放到Store的 State中进行存储。
组件中访问State中的数据的第一种方式:
this.$store.state.要访问的数据
组件中访问State中的数据的第二种方式:
// 从vuex 中按需导入 mapState 函数
import { mapState } from ‘Vuex’
//通过刚才导入的 mapState 函数,将当前组件需要的去全局数据,映射为当前组件的computed计算属性
computed:{
...mapState([ 'count'])
}
② Mutation:用于变更 Store 中的数据
-
只能通过 mutation 变更 Store 数据,不可以直接操作 Store 中的数据。
-
通过这种方式虽然操作起来稍微繁琐一些,但是可以集中监控所有数据的变化。
export default new Vuex.Store({ state:{ count:0 }, mutations:{ add(state,第二个外界传递参数){ //变更状态 state.count++ } }, })
访问 mutation 中的数据 commit 专门用来触发 mutation 函数
this.$store.commit( 'add' ,要传递的参数值)
触发mutations的第二种方式:
//1.从vuex中按需导入mapMutations函数
import { mapMutations } from 'vuex'
//通过导入的mapMutations函数,将需要的mutations函数,映射为当前组件的methods方法:
//2. 将指定的mutations函数,映射为当前组件的methods函数
methods:{
...mapMutations{[ 'add','addN' ]}
}'
③ Action: 用于处理异步任务 (mutation不支持异步任务处理)
如果通过异步操作变更数据,必须通过Action,而不能使用 Mutation, 但是在 Action中还是要通过触发 Mutation的方式间接变更数据。
定义actions
actions:{
//在 actions 中 不能直接修改 state中的数据
// 必须通过 context.commit() 触发某个 mutation才行
addAsync(context,step) {
setTimeout(() => {
context.commit( 'add' )
},1000)
}
}
})
触发actions
methods:{
handle() {
//dispatch 函数 专门用来触发 action
this.$store.dispatch( 'addAsync' ,number)
}
}
触发actions的第二种方式:
//从vuex 中按需导入 mapActions函数
import { mapActions } from 'vuex'
//通过导入的 mapActions函数,映射为当前组件的 methods函数
methods:{
...mapActions({ 'addAsync','addNASycn' ]}
}
④ Getter: 用于对 Store 中的数据进行加工(包装)处理形成新的数据。
- Getter 可以对 Store 中已有的数据加工处理之后形成新的数据,类似Vue的计算属性。
- Store 中数据发生变化,Getter的数据也会跟着变化。
定义 getter
const store = new Vuex.Store({
state:{
count:0
},
getters:{
showNum:state => {
return '当前最新的数值是 [ ' + state.count + ' ] '
},
}
})
使用 getters 的第一种方式
this.$store.getters.showNum
使用 getters 的第二种方式
import { mapGetters } from 'vuex'
computed:{
...mapGetters([ 'showNum' ])
}