Vuex 使用方法(简单易懂)

Vuex是在Vue中实现集中式状态(数据)管理的一个Vue插件,对vue应用中多个组件的共享状态进行集中式的管理(读/写),也是一种组件间通信的方式,且适用于任意组件间通信。

Vuex的使用方法:

一、安装

npm install vuex --save

使用npm进行安装

二、引入

新建文件:src/store/index.js

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

Vue.use(Vuex)

export default new Vuex.Store({
  state: {
    count: 2
  },
  //   执行对state中数据的修改写在mutations里面
  mutations: {
    addOne(state, step) {
      state.count += step
    }
  },
  //   执行异步操作时写在actions里面
  actions: {
    addMin(context, step) {
      setTimeout(() => {
        context.commit('addOne', step)
      }, 1000)
    }
  },
//   对state中的数据进行加工,相当于computed
  getters: {
    showNum(state) {
      return '最新的count值为' + state.count
    }
  }
})

在main.js中引入storesss

import Vue from 'vue'
import App from './App.vue'
import store from './store/index.js'

Vue.config.productionTip = false

new Vue({
  store,
  render: h => h(App),
}).$mount('#app')

 三、使用

1、state

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

  state: {
    count: 2
  },

访问方式:

在组件中访问State的方式:
1this.$store.state.全局数据名称  如:this.$store.state.count
2先按需导入mapState函数: import { mapState } from 'vuex'
然后数据映射为计算属性: computed:{ ...mapState(['全局数据名称']) }
使用:例如:{{count}}

本文只对第一种方式做出演示:

 

我是数字{{ $store.state.count }}

2.Mutation

Mutation用于修改$store中的数据,第一个参数为state,可以自行添加参数

  //   执行对state中数据的修改写在mutations里面
  mutations: {
    addOne(state, step) {
      state.count += step
    }
  },

使用:

第一种方式:this.$store.commit('xxx')
第二种方式:import { mapMutations } from 'vuex'
            methods:{
              ...mapMutations(['xxx'])
            }
调用:this.xxx

演示:

  addOne() {
      this.$store.commit('addOne', 1)
    },

3.Action

在vuex中我们使用Action来执行异步操作。异步操作都写在actions里面

  actions: {
    addMin(context, step) {
      setTimeout(() => {
        context.commit('addOne', step)
      }, 1000)
    }
  },

使用方法:

第一种:this.$store.dispatch('xxx')
第二种:import { mapActions } from 'vuex'
        methods:{
          ...mapMutations(['xxx'])
        }
使用:this.xxx

演示:

addMin(){
        this.$store.dispatch('addMin',1)
    }

4.Getter

当state中的数据需要经过加工后再使用时,可以使用getters加工。

  getters: {
    showNum(state) {
      return '最新的count值为' + state.count
    }
  }

使用:

第一种:this.$store.getters.xxx
第二种:import { mapGetters } from 'vuex'
        computed:{
          ...mapGetters(['xxx'])
        }

演示:

  

{{$store.getters.showNum}}

你可能感兴趣的:(Vue,vue.js,javascript,前端)