安装依赖

  1. npm install vuex --save
  2. npm install axios --save

Vuex Store

新建 store 文件夹,下面新建 index.js

  1. import Vue from "vue";
  2. import Vuex from "vuex";
  3. Vue.use(Vuex);
  4. export default new Vuex.Store({
  5. modules: {
  6. Product,
  7. Cart
  8. }
  9. });

然后在 main.js 中添加 store

  1. ...
  2. import store from "./store";
  3. ...
  4. new Vue({
  5. store,
  6. render: h => h(App),
  7. }).$mount('#app')

应用状态管理

Vuex 可以用来管理应用的数据状态,一共有四种状态

  1. state
  2. mutations
  3. actions
  4. getters

首先 state 用来定义数据,比如说商品数据

  1. const state = {
  2. productList : []
  3. }

然后定义更新商品数据的方法

  1. const mutations = {
  2. UPDATE_PRODUCT(state, data) {
  3. state.producList = data;
  4. }
  5. }

接着定义动作, 跟服务器进行交互

  1. const actions = {
  2. getProducts({ commit }) {
  3. axios.get("/api/getProducts").then( res => {
  4. commit("UPDATE_PRODUCT", res.data)
  5. })
  6. }
  7. }