image.png
① 能够在 vuex 中集中管理共享的数据,易于开发和后期维护 ② 能够高效地实现组件之间的数据共享,提高开发效率 ③ 存储在 vuex 中的数据都是响应式的,能够实时保持数据与页面的同步
一般情况下,只有组件之间共享的数据,才有必要存储到 vuex 中;对于组件中的私有数据,依旧存储在组件 自身的 data 中即可。
npm install vuex --saveimport Vuex from 'vuex'
Vue.use(Vuex)const store = new Vuex.Store({
// state 中存放的就是全局共享的数据
state: { count: 0 }
})Vuex 中的主要核心概念如下:
state 提供唯一的公共数据源,所有共享的数据都要统一放到 Store 的 State 中进行存储。
// 创建store数据源,提供唯一公共数据
const store = new Vuex.Store({
state: { count: 0 }
})第一种方式组件访问 State 中数据this.$store.state.全局数据名称第二种方式组件访问 State 中数据import { mapState } from 'vuex'通过刚才导入的 mapState 函数,将当前组件需要的全局数据,映射为当前组件的 computed 计算属性:
computed: {
...mapState(['count'])
}第一种方式Mutation 用于变更 Store中 的数据。① 只能通过 mutation 变更 Store 数据,不可以直接操作 Store 中的数据。 ② 通过这种方式虽然操作起来稍微繁琐一些,但是可以集中监控所有数据的变化。
image.png
image.png
commit的作用就是调用 mutation参数** this.$store.commit('addN',5)**
第二种方式.触发 mutations 的import { mapMutations } from 'vuex'通过刚才导入的 mapMutations 函数,将需要的 mutations 函数,映射为当前组件的 methods 方法:
methods: {
...mapMutations(['add', 'addN'])
}第一种方式触发 actionsimage.png
image.png
第二种方式触发 actionsimport { mapActions } from 'vuex'通过刚才导入的 mapActions 函数,将需要的 actions 函数,映射为当前组件的 methods 方法:
methods: {
...mapActions(['addASync', 'subNASync'])
numSub2(){
this.subAsync()
},
}Getter 用于对 Store 中的数据进行加工处理形成新的数据。 ① Getter 可以对 Store 中已有的数据加工处理之后形成新的数据,类似 Vue 的计算属性。 ② Store 中数据发生变化,Getter 的数据也会跟着变化
// 定义 Getter
const store = new Vuex.Store({
state: {
count: 0
},
getters: {
showNum: state => {
return '当前最新的数量是【'+ state.count +'】'
}
}
})第一种方式使用 gettersthis.$store.getters.名称第二种方式使用 gettersimport { mapGetters } from 'vuex'
computed: {
...mapGetters(['showNum'])
}https://gitee.com/zhangzanzz007/vuex- demo1 https://gitee.com/zhangzanzz007/vuex- dem02
本文系转载,前往查看
如有侵权,请联系 cloudcommunity@tencent.com 删除。
本文系转载,前往查看
如有侵权,请联系 cloudcommunity@tencent.com 删除。