vuex的常规使用

目录

一、安装

二、配置

三、使用

1、基本使用

2、组件绑定的辅助函数

3、Module


一、安装

npm install --save vuex
#OR
yarn add vuex

注:指定版本在vuex后加上“@版本号”即可;如:yarn add vuex@2.0.0

二、配置

1、创建js文件(/src/store/index.js),位置随意,

import Vue from "vue";
import Vuex from "vuex";
Vue.use(Vuex);

const store = new Vuex.Store({
    // state 类似 data
    state: {},
    // getters 类似 computed
    getters: {},
    // mutations 类似methods
    // 更改 store 中的状态的唯一方法(直接变更state中的数据)
    // 写方法对数据做出更改(同步) 使用commit调用
    mutations: {},
    // 使用起来类似mutations方法,
    // 不同点在于提交的是 mutation,而不是直接变更状态
    // 异步操作,使用dispatch调用
    actions: {},
    // 模块
    modules: {},
});

export default store;

2、配置main.js

import Vue from "vue";
import App from "./App.vue";
// 1.引入上一步创建的js文件,路径按照自己创建的写
import store from "./store/index";

new Vue({
    store, // 2.挂载
    render: (h) => h(App),
}).$mount("#app");

三、使用

1、基本使用

/src/store/index.js

import Vue from "vue";
import Vuex from "vuex";
Vue.use(Vuex);
const store = new Vuex.Store({
    // state 类似 data
    state: {
        product: "杯子",
        price: 100,
        discount: 0.6,
        total: 0,
    },
    // getters 类似 computed
    getters: {
        // 折扣价
        getDiscount(state) {
            return state.price * state.discount;
        },
    },
    // mutations 类似methods
    // 写方法对数据做出更改(同步) 使用commit调用
    mutations: {
        // 计算总价
        // 第 1 个参数:默认参数state, 
        // 第 2 个参数:store.commit 传入额外的参数,即 mutation 的 载荷(payload)
        // 在大多数情况下,载荷应该是一个对象
        // 使用常量替代 mutation 事件类型
        GET_TOTAL(state, n) {
            return (state.total = state.price * state.discount * n);
        },
    },
    // 使用起来类似mutations方法,
    // 不同点在于是异步操作,使用dispatch调用
    actions: {},
    // 模块
    modules: {},
});
export default store;

页面的使用

<template>
    <div class="product">
        <p>产品:{{product}}</p>
        <p>单价:{{price}}</p>
        <p>折扣:{{discount}}</p>
        <p>数量:<input type="text" v-model="number"></p>
        <p>总价:{{total}}</p>
        <button @click="getTotal">计算总价</button>
    </div>
</template>
<script>
export default {
    name: "product",
    // 组件
    components: {},
    data: function () {
        return {
            number: 0,
        };
    },
    computed: {
        product() {
            return this.$store.state.product;
        },
        price() {
            return this.$store.state.price;
        },
        discount(){
            return this.$store.getters.getDiscount;
        },
        total() {
            return this.$store.state.total;
        },
    },
    methods: {
        getTotal() {
            this.$store.commit("GET_TOTAL", this.number);
        },
    },
    // 页面初始化
    created: function () {},
};
</script>
<style>
</style>

2、组件绑定的辅助函数

mapStage

// 页面组件中
import { mapState } from "vuex";
export default {
    computed: {
        // 使用对象展开运算符将 state 混入 computed 对象中
        ...mapState([
            // 映射 price 为 store.state.price
            'price',
            'total'
        ]),
    }
}

若想将state属性重命名,使用对象形式

...mapState({
    // 箭头函数可使代码更简练
    goodsPrice: state => state.price,
    // 传字符串参数 'total' 等同于 `state => state.total`
    priceTotal: 'total'
}),

mapGetters

// 页面组件中
import { mapState, mapGetters } from "vuex";
export default {
    computed: {
        // 使用对象展开运算符将 state 混入 computed 对象中
        ...mapState([
            // 映射 price 为 store.state.price
            'price',
            'total'
        ]),
        // 使用对象展开运算符将 getter 混入 computed 对象中
        ...mapGetters([
            'getDiscount'
        ])
    }
}

若想将state属性重命名,使用对象形式

...mapGetters({
    discount: 'getDiscount'
}),

mapMutations

import { mapMutations } from 'vuex'
export default {
    methods: {
        // 使用对象展开运算符将 mutation 混入 methods 对象中
        ...mapMutations([
            'GET_TOTAL', 
        ]),
    },
}
...mapMutations({
    getTotal: 'GET_TOTAL', 
}),

参数直接在调用时传入即可

<button @click="getTotal(number)">计算总价</button>

mapActions

mapActions用法与mapMutations相同

3、Module

当应用变得非常复杂时,将 store 分割成模块(module)。每个模块拥有自己的 state、mutation、action、getter、甚至是嵌套子模块。

目录结构

在/src/store文件夹下可按下面的项目结构示例创建

├── index.js          # 我们组装模块并导出 store 的地方
├── actions.js        # 根级别的 action
├── mutations.js      # 根级别的 mutation
├── getters.js        # 根级别的 getters
└── modules
    ├── A.js          # A模块
    └── B.js          # B模块
// index.js
import Vue from "vue";
import Vuex from "vuex";
Vue.use(Vuex);

import getters from "./getters";
import mutations from "./mutations";
import actions from "./actions";

import user from "./modules/user";

const store = new Vuex.Store({
    // state 类似 data
    state: {},
    // getters 类似 computed
    getters,
    mutations,
    actions,
    modules: {
        user,
    },
});

export default store;
// actions.js
const actions = {};

export default actions;

// mutations.js
const mutations = {
    // 计算总价:第一个参数为默认参数state, 后面的参数为页面操作传过来的参数
    getTotal(state, n) {
        return (state.total = state.price * state.discount * n);
    },
};

export default mutations;
// getters.js
const getters = {
    // 折扣价
    getDiscount(state) {
        return state.price * state.discount;
    },
};

export default getters;
// 模块基础代码
const module = {
    state: {},
    mutations: {},
    actions: {},
    getters: {},
};

export default module;

命名空间

默认情况下,模块内部的 action、mutation 和 getter 是注册在全局的,可以通过添加 namespaced: true 的方式使其成为带命名空间的模块。

const store = new Vuex.Store({
  modules: {
    A: {
      namespaced: true,

      // 模块内容(module assets)
      state: () => ({ ... }), // 模块内的状态已经是嵌套的了,使用 `namespaced` 属性不会对其产生影响
      getters: {
        aget () { ... } // -> getters['A/aget']
      },
      actions: {
        aact () { ... } // -> dispatch('A/aact')
      },
      mutations: {
        amutat () { ... } // -> commit('A/amutat')
      },

      // 嵌套模块
      modules: {
        // 继承父模块的命名空间
        B: {
          state: () => ({ ... }),
          getters: {
            bget () { ... } // -> getters['A/bget']
          }
        },

        // 进一步嵌套命名空间
        C: {
          namespaced: true,

          state: () => ({ ... }),
          getters: {
            cget () { ... } // -> getters['A/C/cget']
          }
        }
      }
    }
  }
})

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值