vuex 快速上手,具体使用方法总结(含使用例子)

网上有关vuex的文章很多,但有些比较复杂,这篇文章能让你快速使用vuex:

vuex 用处:管理全局状态(类似全局变量,每个组件都能访问到)

结构:

  • state 存放状态
  • mutations state成员操作(修改state值唯一的方法)
  • getters 加工state成员给外界
  • actions 异步操作
  • modules 模块化状态管理

 

vuex 用法:

1. 安装:npm install vuex --save (安装vuex保存到本地)

2. 创建js文件(见下图,这里我随意命名为store.js)

3.然后我们在main.js文件中:

     3.1 引入文件(根据自己的路径写): import store from './store.js';

     3.2 在vue实例全局引入store对象:new Vue({store})

 

以上步骤就完成了,接下来是具体使用方法

 

//下面是一个js文件,用最简单最全的例子展示了全局数据 city 和 cityID 的声明以及改变的方法;
import Vue from 'vue';
import Vuex from 'vuex';
Vue.use(Vuex);
const store = new Vuex.Store({
  state: {
    city: '深圳',
    cityID: "1"
  },
  getters: {
    getCity(state) { //方法名随意,主要是来承载变化的city的值,下面mutations,actions里面的方法名也是随意定的
      return state.city
    },
    getCityId() { //方法名随意,主要是用来承载变化的cityID的值,下面mutations,actions里面的方法名也是随意的
      return state.cityID
    }
  },
  mutations: {
    setCity(state, value) {
      state.city = value;
    },
    setCityID(state, value) {
      state.cityID = value;
    }
  },
  actions: {
    selectCity(context, params) {
      context.commit('setCity', params.city);
    },
    selectCityID(context, params) {
      context.commit('setCityID', params.id);
    }
  }
});
export default store;

 

获取和修改state有使用辅助函数和不使用两种方法,如果使用,请在使用的文件中添加:

import {mapState,mapGetters,mapMutations,mapActions} from 'vuex'

用到里面哪个就引入哪个,如果不使用则不需要添加。
 

获取state的方法:

1.不引入 mapState(不使用辅助函数): this.$store.state
2.引入 mapState(使用辅助函数):
computed: {
    //设置别名,起到简化代码的作用,比如this.$store.state.cityID可以用this.cId替代
    // 方法一:
    ...mapState({
      cId: state => state.cityID,
      cname: state => state.city
    }),
    // 方法二:
    ...mapState({
      cId: "cityID",
      cname: "city"
    }),
    // 方法三(不设置别名,直接使用this.cityID即可):
    ...mapState(["cityID", "city"]),
    // 方法四(通过mapGetters):
    ...mapGetters(["getCity",'getCityId'])
  }

修改state的方法:

1.mutations:

1: 用this.$store.commit执行mutation里的方法 
this.$store.commit("setCityID",6);
2:使用辅助函数
methods:{
...mapMutations(['setCity','setCityID']),
}
//通过this.setCity(6),this.selectCityID({id:6})调用

2.actions:

1: 用this.$store.dispatch执行actions里的方法 
this.$store.dispatch("selectCityID",{id:6});
2:使用辅助函数
methods:{
...mapActions(['selectCity','selectCityID]),
}

//通过this.setCity(6),this.selectCityID({id:6})调用
 
posted @ 2019-12-23 16:25  william_new  阅读(1341)  评论(0编辑  收藏  举报