vue3中vuex教程

什么是状态管理

在开发中,我们会的应用程序需要处理各种各样的数据,这些
数据需要保存在我们应用程序中的某一个位置,对于这些数据
的管理我们就称之为是 状态管理。

  • 在Vue开发中,我们使用组件化的开发方式;
  • 而在组件中我们定义data或者在setup中返回使用的数据,
    这些数据我们称之为state;
  • 在模块template中我们可以使用这些数据,模块最终会被渲染成DOM,我们称之为View;
  • 在模块中我们会产生一些行为事件,处理这些行为事件时,
    有可能会修改state,这些行为事件我们称之为actions;

复杂的状态管理

当我们的应用遇到多个组件共享状态时,单向数据流的简洁性很容易被破坏:

  • 多个视图依赖于同一状态;
  • 来自不同视图的行为需要变更同一状态;

Vuex的状态管理

管理不断变化的state本身是非常困难的:

状态之间相互会存在依赖,一个状态的变化会引起另一个状态的变化,View页面也有可能会引起状态的变化;
当应用程序复杂时,state在什么时候,因为什么原因而发生了变化,发生了怎么样的变化,会变得非常难以控制和追踪;

这就是Vuex背后的基本思想,它借鉴了Flux、Redux、Elm(纯函数语言,redux有借鉴它的思想):

Vuex的状态管理

npm install vuex@next

创建Store

store本质上是一个容器,它包含着你的应用中大部分的状态(state);每一个Vuex应用的核心就是store(仓库)

注意
Vuex和单纯的全局对象有什么区别呢?

  1. 第一:Vuex的状态存储是响应式的,当Vue组件从store中读取状态的时候,若store中的状态发生变化,那么相应的组件也会被更新;
  2. 第二:你不能直接改变store中的状态,改变store中的状态的唯一途径就显示提交 (commit) mutation;

组件中使用store

在模板中使用;
在options api中使用,比如computed;
在setup中使用;

案列
src下面创建store文件夹,里面创建index.js

import {
    
    
    createStore
} from 'vuex'


const store = createStore({
    
    
    state() {
    
    
        return {
    
    
            counter: 0,
            name: "张三",
            age: 23,
            sex: "男"
        }
    },
    mutations: {
    
    
        increment(state) {
    
    
            state.counter++
        },
        decrement(state) {
    
    
            state.counter--
        }
    }
})

export default store

在组件中使用

<template>
  <div>
    {
    
    {
    
     $store.state.counter }}
    <button @click="add">+1</button>
    <button @click="decren">-1</button>
    <hr />
    <p>{
    
    {
    
     name }}</p>
    <p>{
    
    {
    
     age }}</p>
    <p>{
    
    {
    
     sex }}</p>
  </div>
</template>

<script>
import {
    
     useStore, mapState } from "vuex";
import {
    
     computed } from "vue";
export default {
    
    
  setup() {
    
    
    const store = useStore();
    const add = () => {
    
    
      store.commit("increment");
    };
    const decren = () => {
    
    
      store.commit("decrement");
    };
   
    return {
    
     add, decren };
  },
};
</script>

<style>
#app {
    
    
  font-family: Avenir, Helvetica, Arial, sans-serif;
  -webkit-font-smoothing: antialiased;
  -moz-osx-font-smoothing: grayscale;
  text-align: center;
  color: #2c3e50;
  margin-top: 60px;
}
</style>

单一状态树

Vuex 使用单一状态树:

  • 用一个对象就包含了全部的应用层级的状态;
  • 采用的是SSOT,Single Source of Truth,也可以翻译成单一数据源;

单一状态树的优势:

  • Vuex也使用了单一状态树来管理应用层级的全部状态;
  • 单一状态树能够让我们最直接的方式找到某个状态的片段,而且在之后的维护和调试过程中,也可以非常方便的管理和维护;

组件获取状态

我们可以使用计算属性或者使用mapState的辅助函数:

在setup中使用mapState

  1. 在setup中如果我们单个获取装是非常简单的:
    通过useStore拿到store后去获取某个状态即可;
  2. 默认情况下,Vuex并没有提供非常方便的使用mapState的方式,这里我们进行了一个函数的封装:
import {
    
    
    computed
} from 'vue'
import {
    
    
    useStore,
    mapState
} from 'vuex'

export default function useState(mapper) {
    
    
    const store = useStore()
    const stateFns = mapState(mapper)
    const state = {
    
    }
    Object.keys(stateFns).forEach(key => {
    
    
        state[key] = computed(stateFns[key].bind({
    
    
            $store: store
        }))
    })
    return state
}

组件中使用

const state = useState({
    
    
      name: (state) => state.name,
    });
    return

getters的基本使用

某些属性我们可能需要经过变化后来使用,这个时候可以使用getters:

   getters: {
    
    
        totalPrice(state) {
    
    
            let totalPrice = 0;
            for (const book of state.books) {
    
    
                totalPrice = +book.count * book.price
            }
            return totalPrice;
        }
    },

getters可以接收第二个参数:

getters: {
    
    
        totalPrice(state, getters) {
    
    
            let totalPrice = 0;
            for (const book of state.books) {
    
    
                totalPrice = +book.count * book.price
            }
            return totalPrice + '---'+getters.myName;
        },
        myName(state) {
    
    
            return state.name
        }
    },

mapGetters的辅助函数

在setup中使用
单独定义一个js文件

export function useGetters(mapper) {
    
    
    const store = useStore()
    const stateFns = mapGetters(mapper)
    const state = {
    
    }
    Object.keys(stateFns).forEach(key => {
    
    
        state[key] = computed(stateFns[key].bind({
    
    
            $store: store
        }))
    })
    return state
}

组件中引用

setup() {
    
    
    const stateFns = useGetters(["totalPrice"]);
    return {
    
     ...stateFns };
  },

Mutation基本使用

更改 Vuex 的 store 中的状态的唯一方法是提交 mutation:

 mutations: {
    
    
        increment(state) {
    
    
            state.counter++
        },
        decrement(state) {
    
    
            state.counter--
        },
        incrementN(state, payload) {
    
    
            state.counter += payload.n
        }
    }
const incre = () => {
    
    
      store.commit("incrementN", {
    
     n: 100, name: 20 });
    };

Mutation常量类型

在这里插入图片描述
要引入js文件
在这里插入图片描述
在组件中使用首先引入js文件

store.commit({
    
    
        type: ADD_NUMBER,
        count: 1200,
      });

mapMutations辅助函数

我们也可以借助于辅助函数,帮助我们快速映射到对应的方法中:
在这里插入图片描述

mutation重要原则

在这里插入图片描述

actions的基本使用

Action类似于mutation,不同在于:

  • Action可以包含任意异步操作;
  • Action提交的是mutation,而不是直接变更状态;
actions: {
    
    
        // 放函数
        incrementAction(context) {
    
    
            context.commit('increment')
        }
    }

这里有一个非常重要的参数context:

  • context是一个和store实例均有相同方法和属性的context对象;
  • 所以我们可以从其中获取到commit方法来提交一个mutation,或者通过 context.state 和 context.getters 来获取 state 和 getters;
  • 但是为什么它不是store对象呢?这个等到我们讲Modules时再具体来说;

actions的分发操作

分发使用的是 store 上的dispatch函数;

setup() {
    
    
    const store = useStore();
    const increment = () => {
    
    
      setTimeout(() => {
    
    
        store.dispatch("incrementAction");
      }, 2000);
    };
    return {
    
     increment };
  },
 decrementAuction(context,payload){
    
    
      context.commit('incrementN',{
    
    n:payload.num})
  }

actions的辅助函数

action也有对应的辅助函数:
在这里插入图片描述

actions的异步操作

我们可以通过让action返回Promise,在Promise的then中来处理完成后的操作;
在这里插入图片描述

module的基本使用

什么是Module?
由于使用单一状态树,应用的所有状态会集中到一个比较大的对象,当应用变得非常复杂时,store 对象就有可能变得相当臃肿;

  • 每个模块拥有自己的 state、mutation、action、getter、甚至是嵌套子模块;
    在这里插入图片描述

module的局部状态

对于模块内部的 mutation 和 getter,接收的第一个参数是模块的局部状态对象:

getters: {
    
    
      doubleHomeCounter(state, getters, rootState, rootGetters) {
    
    
        return state.homeCounter * 2
      },
      otherGetter(state) {
    
    
        return 100
      }
    },
    mutations: {
    
    
      increment(state) {
    
    
        state.homeCounter++
      }
    },
actions: {
    
    
      incrementAction({
     
     commit, dispatch, state, rootState, getters, rootGetters}) {
    
    
        commit("increment")
        commit("increment", null, {
    
    root: true})
 
      },
      doubleHomeCounter2({
     
     commit}){
    
    
          commit("increment")
      }
    }

module的命名空间

默认情况下,模块内部的action和mutation仍然是注册在全局的命名空间中的:

  • 这样使得多个模块能够对同一个 action 或 mutation 作出响应;
  • Getter 同样也默认注册在全局命名空间;

如果我们希望模块具有更高的封装度和复用性,可以添加 namespaced: true 的方式使其成为带命名空间的模块:

  • 当模块被注册后,它的所有 getter、action 及 mutation 都会自动根据模块注册的路径调整命名;

module修改或派发根组件

如果我们希望在action中修改root中的state,那么有如下的方式:
在这里插入图片描述

module的辅助函数

方式一:通过完整的模块空间名称来查找;
方式二:第一个参数传入模块空间名称,后面写上要使用的属性;
方式三:通过 createNamespacedHelpers 生成一个模块的辅助函数;

在这里插入图片描述
在这里插入图片描述

对useState和useGetters修改

在这里插入图片描述
在这里插入图片描述

自定义指令 format-time bug修复

在这里插入图片描述

nexttick

官方解释:将回调推迟到下一个 DOM 更新周期之后执行。在更改了一些数据以等待 DOM 更新后立即使用它。

historyApiFallback

在这里插入图片描述

猜你喜欢

转载自blog.csdn.net/qq_41961239/article/details/120809185