vuex数据共享

  1. vuex的基本配置:

1.1 安装vuex依赖包:

npm install vuex --save

1.2 在src目录下创建store.js文件

import Vue from 'vue'
import Vuex from 'vuex'

Vue.use(Vuex)

export default new Vuex.Store({
    
    
  state: {
    
    
    
  },
  mutations: {
    
    },
  actions: {
    
    },
})

1.3.把store对象挂载到vue实例中

import store from './store'

new Vue({
    
    
  // 将创建的共享数据对象,挂载到Vue实例中
  // 所有的组件就可以直接从store中获取全局数据
  store,
  render: (h) => h(App),
}).$mount('#app')

2.Vuex的核心概念—state:

state提供唯一的公共数据源,所有的共享的数据都要统一放到Store中的state中进行储存

如果在state中存了一个Count数据

state:{
    
     Count:0 }

2.1state访问数据的第一种方式:

// this.$store.state.全局数据名称
this.$store.state.Count

2.2 state访问数据的第二种方式:

  // 从vuex中按需导入mapState 函数
import {
    
     mapState } from 'vuex'

通过导入的mapState函数,将当前组件需要的全局数据映射为当前组件的computed计算属性,
在使用的时候直接当计算属性使用就行

computed: {
    
    
    ...mapState(['Count']),
  },

3.vuex核心概念—mutation
在vuex中,不能直接操作Store中的数据,只能通过mutation变更store中的数据
通过这种方式虽然操作起来稍微繁琐,但是可以集中监控所有的数据变化,便于维护
3.1 mutation的第一种用法:

mutations: {
    
    
	// step是参数
    add(state,step) {
    
    
      state.Count++
    },
methods: {
    
    
    btnhandler1() {
    
    
    // 用this.$store.commit('mutation中的函数名',参数)
    //commit的作用是调用某个mutation函数
      this.$store.commit('add',3)
    },
  },

3.2 mutation的第二种用法:

// 从vuex按需导入mapMutations函数
import {
    
     mapMutations } from 'vuex'

通过导入的mapMutations函数,将需要的mutations中的函数,映射为当前组件的methods方法

methods: {
    
    
    ...mapMutations(['add']),
    
  },

4.vuex核心概念----Action:
如果通过异步操作变更数据,必须通过Action,而不能使用Mutation,但是在Action中还是要通过触发Mutation的方式间接变更数据
4.1Action的第一种用法:

addAsync(context, step) {
    
    
      setTimeout(() => {
    
    
        // 在actions中不能直接修改state中的数据
        // 必须通过context.commit()触发某个mutation才行
        context.commit('add', step)
      }, 1000)
    },
btnhandler4() {
    
    
		// dispatch函数,专门用来触发action
      this.$store.dispatch('addAsync', 5)
    },

4.2Action的第二种用法:

// 从vuex中按需导入mapActions函数
import {
    
    mapActions} from 'vuex'

通过mapActions函数将actions中的函数映射为当前组件的methods方法

methods: {
    
    
    
    ...mapActions(['addAsync','addNAsync']),
    
  },

5.vuex的核心概念—Getter
① .Getter用于对store中的数据进行加工处理形成新的数据,类似Vue的计算属性
② . store中数据发生变化,Getter中的数据也会跟着变化
5.1Getter的第一种用法:

getters: {
    
    
    showNum(state) {
    
    
      return '当前最新的Count值为' + state.Count
    }
  }
//使用 this.$store.getters.名称
this.$store.getters.showNum

5.2 第二种用法:

import {
    
    mapGetters} from 'vuex'
computed:{
    
    
...mapGetters(['showNum'])
}

猜你喜欢

转载自blog.csdn.net/weixin_44738158/article/details/121113816