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);

未完待续

  • 23
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 21
    评论
评论 21
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值