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']),
  },

修改state的方法:

1.不引入 mapState(不使用辅助函数):

方法一: 用this.$store.commit执行mutation里的方法 
//this.$store.commit("setCityID", 6);

方法二: 用 this.$store.dispatch执行actions里的方法
//this.$store.dispatch("selectCity", { id: 6});

2.引入 mapState(使用辅助函数),和获取state一样能设置别名,下面不配置别名:

methods: {
    ...mapActions(['cityID','selectCityID']),
    changeId(params) { //params为要修改的数,比如6
      this.selectCityID({ id:params });
       console.log(this.$store.state);//这时候打印出来cityID变为6了
    }
  },

 

 

 

posted @ 2023-04-01 12:35  JackieDYH  阅读(6)  评论(0编辑  收藏  举报  来源