Vuex学习

Vuex

Vuex 是实现组件全局状态(数据)管理的一种机制,可以方便的实现组件之间数据的共享。

1、安装vuex

#npm安装
npm install vuex --save
#yarn安装
yarn add vuex --save

#安装vuex 启动 报错 “export ‘watch‘ was not found in ‘vue‘
#如果你的vue版本是 2.X ,将vuex升到 3.X.X 就能够解决
npm install --save vuex@3.6.2

#如果你的vue版本是 3.X ,将vuex升到 4.X.X 就能够解决
npm install --save vue@3.0.2
npm install --save vuex@4.0.0

2、导入和注册vuex

在src目录下创建store目录并在目录下创建store.js,最后在main.js中引入store

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

Vue.use(Vuex)

export default new Vuex.Store({
    //State 提供唯一的公共数据源,所有共享的数据都要统一放到 Store 的 State 中进行存储。
    // state 中存放的就是全局共享的数据
    state: { count: 0 },
    //Mutation 用于变更 Store中 的数据
    //①只能通过 mutation 变更 Store 数据,不可以直接操作 Store 中的数据。
    //②通过这种方式虽然操作起来稍微繁琐一些,但是可以集中监控所有数据的变化。
    mutations: {
        //自增不带参数
        add(state) {
            state.count++
        },
        //自增带参数
        add1(state, step) {
            state.count += step
        },
        //自减不带参数
        sub(state) {
            state.count--
        },
        //自减带参数
        sub1(state, step) {
            state.count -= step
        }
    },
    //Action 用于处理异步任务
    //如果通过异步操作变更数据,必须通过 Action,而不能使用 Mutation,但是在 Action 中还是要通过触发Mutation 的方式间接变更数据。
    actions: {
        addAsync(context) {
            setTimeout(() => {
                context.commit('add')
            }, 1000)
        },
        subAsync(context) {
            setTimeout(() => {
                context.commit('sub')
            }, 1000)
        },
        add1Async(context, step) {
            setTimeout(() => {
                context.commit('add1', step)
            }, 1000)
        }, sub1Async(context, step) {
            setTimeout(() => {
                context.commit('sub1', step)
            }, 1000)
        }
    },
    //Getter 用于对 Store 中的数据进行加工处理形成新的数据。
    //①Getter 可以对 Store 中已有的数据加工处理之后形成新的数据,类似 Vue 的计算属性。
    //②Store 中数据发生变化,Getter 的数据也会跟着变化。
    getters: {
        showNum: state => {
            return '当前最新的数量是【' + state.count + '】'
        }
    }
}
);

3、组件访问方式一

<template>
  <div>
    <h3>$store.state.全局数据访问</h3>
    <h3>当前最新制为:{{ $store.state.count }}</h3>
    <button @click="sub">内置-1</button>
    <button @click="sub1(3)">传递参数-</button>
        <button @click="subAsync">异步内置-1</button>
    <button @click="sub1Async(3)">异步传递参数-</button>
     <h3>$store.getters.名称</h3>
     <h3>{{$store.getters.showNum}}</h3>
  </div>
</template>
<script>
export default {
  data() {
    return {};
  },
  methods: {
    sub() {
        //this.$store.commit()触发mutations,不带参数
      this.$store.commit("sub");
    },
    sub1(num) {
        //this.$store.commit()触发mutations,带参数
      this.$store.commit("sub1", num);
    },
    subAsync() {
        //this.$store.dispatch()触发actions,不带参数
      this.$store.dispatch("subAsync");
    },
    sub1Async(num) {
        //this.$store.dispatch()触发actions,带参数
      this.$store.dispatch("sub1Async", num);
    },
  },
};
</script>

4、组件访问方式二

<template>
  <div>
    <h3>mapState将全局数据,映射为当前组件的计算属性</h3>
    <h3>当前最新制为:{{ count }}</h3>
    <button @click="add">内置+1</button>
    <button @click="add1(3)">传递参数+</button>
    <button @click="addAsync">异步内置+1</button>
    <button @click="add1Async(3)">异步传递参数+</button>
     <h3>mapGetters方式</h3>
     <h3>{{$store.getters.showNum}}</h3>
  </div>
</template>
<script>
//从 vuex 中按需导入 mapState 函数
//从 vuex 中按需导入 mapMutations 函数
//从 vuex 中按需导入 mapActions 函数
//从 vuex 中按需导入 mapActions 函数
import { mapState, mapMutations, mapActions,mapGetters } from "vuex";
export default {
  data() {
    return {};
  },
  methods: {
    //将指定的 mutations 函数,映射为当前组件的 methods 函数
    ...mapMutations(["add1", "add"]),
    //将指定的 actions 函数,映射为当前组件的 methods 函数
    ...mapActions(["addAsync", "add1Async"]),
  },
  computed: {
    //将全局数据,映射为当前组件的计算属性 
    ...mapState(["count"]),
      //getters 的第二种方式:
    ...mapGetters(['showNum'])
  },
};
</script>

5、Module

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

Vue.use(Vuex)

const moduleA = {
  state: () => ({ ... }),
  mutations: { ... },
  actions: { ... },
  getters: { ... }
}

const moduleB = {
  state: () => ({ ... }),
  mutations: { ... },
  actions: { ... }
}

const store = new Vuex.Store({
  modules: {
    a: moduleA,
    b: moduleB
  }
})

store.state.a // -> moduleA 的状态
store.state.b // -> moduleB 的状态

6、Vuex持久化

安装
yarn add vuex-persistedstate
界面引入
import Vue from 'vue'
import Vuex from 'vuex'
//引入插件
import createPersistedState from 'vuex-persistedstate'

Vue.use(Vuex)

export default new Vuex.Store({
    state: {... },mutations: {...},
    actions: {...},
    getters: {...},
    //vuex持久化
    //默认的存储方式是 localStorage
    plugins: [createPersistedState({
        storage: window.sessionStorage, // 存储方式改为sessionStorage
    })]
}
);
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值