Vuex的初步使用详解

vuex 一般用来解决某些值,在不同的组件中都要用到,如果两个组件经过路由直达传参还好,一旦是跨了好几层路由之间传参,比如想要登录后的token,登录后的用户名。购物车的数量显示等,有些还要实时更新。不可能一直传来传去。这个时候使用Vuex。

vuex

数据保存在state中,想要更改必须通过 Mutations里的方法才能更改。想要调用 Mutations里的方法 必须在Actions 里用commit函数调用。在组件内通过vuex 的dispatch方法调用Actions里的方法。当调用成功了,更改视图。

mutation 必须同步执行  action里的方法可以异步处理

写一个全套例子(包含所有使用方法)

写个store.js

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

Vue.use(Vuex);

const store = new Vuex.Store({
  modules: {
    message: {
      state: {
        orderId: 0
      },
      mutations: {
        SET_ORDER_ID: (state, code) => {
          state.orderId = code;
        }
      },

      actions: {
        // 订单Id
        setOrderId({ commit }, data) {
          // 通知mutations 里的SET_ORDER_ID方法更改
          commit('SET_ORDER_ID', data);
        },
        // 其他方法中调用 actions中方法
        setAdd({ commit, dispatch }, data) {
          let newOrder = data + 100; // 这里假设它要加一百,这就是这个函数的意义。
          dispatch('setOrderId', newOrder);
        }
      }
    },
    colorNumber: {
      state: {
        color: 'green'
      },
      mutations: {
        SET_COLOR: (state, color) => {
          state.color = color;
        }
      },

      actions: {
        // 订单Id
        setOrderId({ commit }, data) {
          // 通知mutations 里的SET_COLOR方法更改
          commit('SET_COLOR', data);
        }
      }
    }
  },
  getters: {
    orderId: state => state.message.orderId,
    color: state => state.colorNumber.color
  }
});

export default store;

main.js中

import store from './store';
new Vue({
  store
  render: h => h(App)
}).$mount('#app');

此时已经可以在组件中用了。

组件中使用vuex中的变量

console.log(this.$store.getters.color)

想要调取vuex中方法更改状态

this.$store.dispatch('setAdd',30);

未完待续

原创文章 112 获赞 173 访问量 4万+

猜你喜欢

转载自blog.csdn.net/weixin_41229588/article/details/105991201