状态管理库之 Vuex

老项目还在用 vuex,来复习一波~

在这里插入图片描述

一、状态管理

  • 应用程序需要处理各种各样的数据,这些数据需要保存在应用程序中的某一个位置,对于这些数据的管理称之为是状态管理
  • vue 页面管理自己的状态
    • 在 Vue 开发中,使用组件化的开发方式
    • 而在组件中定义 data 或者在 setup 中返回使用的数据,这些数据称之为 state
    • 在模块 template 中可以使用这些数据,模块最终会被渲染成 DOM,称之为 View
    • 在模块中会产生一些行为事件,处理这些行为事件时,有可能会修改state,这些行为事件称之为actions

二、复杂的状态管理

  • JavaScript 开发的应用程序,已经变得越来越复杂了
    • JavaScript 需要管理的状态越来越多,越来越复杂
    • 这些状态包括服务器返回的数据、缓存数据、用户操作产生的数据等等
    • 也包括一些 UI 的状态,比如某些元素是否被选中,是否显示加载动效,当前分页
  • 当应用遇到多个组件共享状态时,单向数据流的简洁性很容易被破坏
    • 多个视图依赖于同一状态
    • 来自不同视图的行为需要变更同一状态
  • 是否可以通过组件数据的传递
    • 对于一些简单的状态,确实可以通过 props 的传递或者 Provide 的方式来共享状态
    • 但是对于复杂的状态管理来说,显然单纯通过传递和共享的方式是不足以解决问题的,比如兄弟组件如何共享数据

三、Vuex 的状态管理

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

    • 状态之间相互会存在依赖,一个状态的变化会引起另一个状态的变化,View页面也有可能会引起状态的变化
    • 当应用程序复杂时,state在什么时候,因为什么原因而发生了变化,发生了怎么样的变化,会变得非常难以控制和追踪
  • 将组件的内部状态抽离出来,以一个全局单例的方式来管理

    • 在这种模式下,组件树构成了一个巨大的“视图 View”
    • 不管在树的哪个位置,任何组件都能获取状态或者触发行为
    • 通过定义和隔离状态管理中的各个概念,并通过强制性的规则来维护视图和状态间的独立性,代码会变得更加结构化和易于维护、跟踪
  • Vuex 背后的基本思想,它借鉴了 Flux、Redux、Elm(纯函数语言,redux有借鉴它的思想)

  • 使用

    • 组件可以直接访问 State,但不能直接修改 State,
    • 必须通过 Dispatch 派发一个行为,拿到数据之后
    • 通过 commit Mutations 修改 State

四 、Vuex 的基本使用

vue2:

模板中使用:

  1. 数据不长:{{ $store.state.counter }}
  2. 数据很长,可使用 computed:

computed: {
storeCounter() {
return this.$store.state.counter;
},
}

使用: {{ storeCounter}}

vue3:

  1. 修改 state: commit 提交:store.commit(“changeCounter”)
  2. 获取数据:const { counter } = toRefs(store.state)
  • 安装:npm i vuex
  • 创建文件夹:store=> index.js
import { createStore } from "vuex";
// options:传入对象
const store = createStore({
    // 返回一个对象
  state: () => ({
    counter: 111110,
  }),
  mutations: {
    changeCounter(state) {
      state.counter++
    }
  }
});
export default store
  • 使用

    • main.js 中使用:createApp(App).use(store).mount("#app"),通过插件安装
    • template中访问 counter: <h2>app:{{ $store.state.counter }}</h2>
    • option API中的computed中使用
    export default {
      computed: {
        storeCounter() {
          return this.$store.state.counter;
        },
      },
    };
    
    • setup中使用

      • 解构之后不是响应式
      • 直接赋值给另外一个变量也不是响应式
      • 需要使用 toRefs()
    • 修改 state

      • 组件中 commit 提交:store.commit(“changeCounter”)
      • store 中定义属性 mutation:
        mutations: {
            // 默认传入 state
          changeCounter(state) {
            state.counter++
          }
        }
      
    <script setup>
    import { toRefs } from "vue";
    import { useStore } from "vuex";
    const store = useStore();
    // setup直接赋值
    const setupCounter=store.state.counter
    console.log(store.state.counter);
    // 直接解构
    // const { counter } = store.state
    // toRefs
    const { counter } = toRefs(store.state)
    
    const changeCounter = () => {
      // 提交事件:store 中 mutation 中对应的名称
      store.commit("changeCounter");
      // store.state.counter++
    };
    </script>
    

五、创建 store

  • 每一个 Vuex 应用的核心就是 store(仓库)
    • store本质上是一个容器,它包含着应用中大部分的状态(state)
  • Vuex 和单纯的全局对象区别
    • 第一:Vuex的状态存储是响应式的
      • 当 Vue 组件从store中读取状态的时候,若store中的状态发生变化,那么相应的组件也会被更新
    • 第二:不能直接改变store中的状态
      • 改变 store 中的状态的唯一途径就显示提交 (commit) mutation
      • 这样使得方便的跟踪每一个状态的变化,从而能够通过一些工具帮助更好的管理应用的状态
  • 使用步骤
    • 创建 Store 对象
    • 在 app 中通过插件安装
<template>
  <div class="home">
    <h2>home:{{ $store.state.counter }}</h2>
    <button @click="changeCounter"> +1</button>
  </div>
</template>

<script setup>
    // 通过 hook 的方式拿到我们的 store
import { useStore } from 'vuex'
const store = useStore()
const changeCounter = () => {
  // 提交事件
  store.commit("changeCounter")
  // store.state.counter++
}
</script>
<style lang="less" scoped>

</style>

六、单一状态树

  • Vuex 使用单一状态树
    • 用一个对象就包含了全部的应用层级的状态
    • 采用的是 SSOT,Single Source of Truth,也可以翻译成单一数据源
  • 这也意味着,每个应用将仅仅包含一个 store 实例
    • 单状态树和模块化并不冲突,因为还有 module ,进行了分模块
  • 单一状态树的优势
    • 如果状态信息是保存到多个 Store 对象中的,那么之后的管理和维护等等都会变得特别困难
    • 所以 Vuex 也使用了单一状态树来管理应用层级的全部状态
    • 单一状态树能够以最直接的方式找到某个状态的片段
    • 而且在之后的维护和调试过程中,比较直观,也可以非常方便的管理和维护,但不够灵活

七、状态映射

vue2:

computed: {
// 数组
...mapState(['name','level','avatarURL']), // 返回函数
// 可以改名称
...mapState({
sName:state=>state.name,
sLevel:state=>state.level,
sAvatarURL:state=>state.avatarURL
})
}

vue3:

const store = useStore()
const {name:sname,level:slevel} = toRefs(store.state)
  • state 很多,一般都是直接映射到computed
import { createStore } from "vuex";
const store = createStore({
  state: () => ({
    counter: 111110,
    name: "lisa",
    level: 99,
    avatarURL: "hhhh",
  }),
  mutations: {
    changeCounter(state) {
      state.counter++;
    },
  },
});
export default store;
  • 使用:import { mapState } from 'vuex'

  • 映射方式

    • 通过数组形式映射需要确保名字和 data 中不一致
    • 通过传入对象可以自己自定义名字
  • 适用于 vue2

<template>
  <div class="app">
    <!-- 1. 在模板中直接使用多个状态 -->
    <h2>name:{{ $store.state.name }}</h2>
    <h2>name:{{ $store.state.level }}</h2>
    <h2>name:{{ $store.state.avatarURL }}</h2>
    <!-- 2. 计算属性 (映射状态)-->
    <h1>name:{{ name }}</h1>
    <h1>name:{{ level }}</h1>
    <h1>name:{{ avatarURL }}</h1>
    <!-- 3. 计算属性:对象语法 -->
    <h3>name:{{ sName }}</h3>
    <h3>name:{{ sLevel }}</h3>
    <h3>name:{{ sAvatarURL }}</h3>
  </div>
</template>
<script >
import { computed } from 'vue';
import { mapState } from 'vuex'
export default{
  computed: {
    fullname() {
      return "xxx"
    },
    // 数组
    ...mapState(['name','level','avatarURL']), // 返回函数
      // 可以改名称
    ...mapState({
      sName:state=>state.name,
      sLevel:state=>state.level,
      sAvatarURL:state=>state.avatarURL
    })
  }
}
</script>
    
  • 适用于 vue3:

    • 在 setup 语法中返回的是函数,可以computed一起使用需要结合bind使用

    • 拿到函数

    • 绑定 this

<script setup>
import { computed} from 'vue'
import { useStore, mapState } from 'vuex'

const { name, level, avatarURL } = mapState(['name', 'level', 'avatarURL'])
const store = useStore()
const cName = computed(name.bind({$store:store}))
const clevel = computed(level.bind({$store:store}))
const cavatarURL = computed(avatarURL.bind({$store:store}))
</script>
  • 封装 hooks 函数
import { computed } from 'vue'
import { useStore ,mapState} from 'vuex'
export default function useState(mapper) {
  const store = useStore()
  const stateFnsObj = mapState(mapper)
  const newStates = {}
  Object.keys(stateFnsObj).forEach(key=>{
    newStates[key] = computed(stateFnsObj[key].bind({$store:store}))
  })
  return newStates
}
import useState from "../hooks/useState";
const {name,level} = useState(["name", "level", "avatarURL"]);
  • vue3 推荐方案:直接对store.state 进行解构,结合 toRefs 变成响应式
const store = useStore()
const {name:sname,level:slevel} = toRefs(store.state)

八、getters

  • 相当于组件的computed
import { createStore } from "vuex";
const store = createStore({
  state: () => ({
    counter: 111110,
    users: [
      { id: "111", name: "lisa", age: 33 },
      { id: "131", name: "shawll", age: 33 },
      { id: "141", name: "hsih", age: 43 },
      { id: "151", name: "fef", age: 53 },
      { id: "161", name: "ffb", age: 53 },
    ],
  }),
  mutations: {
    changeCounter(state) {
      state.counter++;
    },
  },
  getters: {
      // 1. 基本使用
    doubleCounter(state) {
      return state.counter * 2;
    },
    totalAge(state) {
      return state.users.reduce((preValue, item) => {
        return item.age + preValue;
      }, 0);
    },
      // 2. 在 getter 属性中使用另外一个getter
    message(state, getters) {
      // getter中使用其他的getters
      return `name为${state.name} totalAge为${getters.totalAge}`;
    },
      // 3. getters 可以返回一个函数,调用这个函数可以传入参数
    getUserById(state) {
     
      return function (id) {
        const friend = state.users.find(item => item.id == id)
        return friend
      }
    }
  },
});
export default store;
  • 使用

    • template中使用
    <template>
      <div>
        <h1>{{$store.getters.doubleCounter}}</h1>
        <h1>totalAge:{{ $store.getters.totalAge }}</h1>
        <h1>message:{{ $store.getters.message }}</h1>
    // 返回一个函数:调用这个函数
        <h1>user:{{ $store.getters.getUserById(111) }}</h1>
      </div>
    </template>
    

八、mapGetters

  • vue2
<script>
import { mapGetters, useStore } from "vuex";
export default {
  computed: {
    ...mapGetters(["doubleCounter", "totalAge", "message"]),
    ...mapGetters(["getUserById"]),
  },
};
</script>
  • vue3
<script setup>
import { computed, toRefs } from "vue";
import { mapGetters } from "vuex";
import { useStore } from "vuex";
const store = useStore();
// 1. 使用 mapGetters
const { message: messageFn } = mapGetters(["message"]);
// const message = computed(messageFn.bind({ $store: store }))
// 2. 直接解构,并且包裹成ref
// const { message } = toRefs(store.getters);
// 3. 针对某一个getters属性使用computed
const message = computed(() => store.getters.message);
</script>

九、Mutation

  • 类似于 methods
  • 更改 Vuex 的 store 中的状态的唯一方法是提交 mutation
<template>
  <div class="home">
    <h2>name:{{ $store.state.name }}</h2>
    <button @click="changeName('小明')">changeName</button>
  </div>
</template>
<script>
// export default {
//   methods: {
//     changeName() {
//       this.$store.commit("changeName");
//     },
//   },
// };
</script>
<script setup>
import { useStore } from "vuex";
const store = useStore();
const changeName = (name) => {
    // 第二个参数可以是对象{{name:"yyyy",count:33}}
  store.commit("changeName",name);
};
</script>
<style lang="less" scoped></style>

  mutations: {
    changeCounter(state) {
      state.counter++;
    },
    changeName(state,payload) {
      state.name = payload
    }
  },
  • 常量
    • 单独一个文件定义mutation类型:mutation_types.js:export const CHANGE_INFO = "changeInfo"
    • 导入:import { CHANGE_INFO } from "./mutation_types";
    • 使用
      • store中:[CHANGE_INFO]

十、mapMutations

  • 组件中不需要 commit 直接修改
  • vue2
<template>
	<div>
        <button @click = "changeName('jujuih')">
    		修改名字        
        </button>
    </div>
</template>
<script>
import { mapMutations } from "vuex";
import { CHANGE_INFO } from "@/store/mutation_types";
export default {
  computed: {},
  methods: {
    btnClick() {
      console.log("btnClick");
    },
    // 直接映射过去了,不需要commit
    ...mapMutations(["changeName", "incrementLevel", CHANGE_INFO]),
  },
};
</script>
  • vue3
<script setup>
// 返回了一个个函数
const mutations = mapMutations(["changeName", CHANGE_INFO]);
const newMutations = {};
Object.keys(mutations).forEach((key) => {
  newMutations[key] = mutations[key].bind({ $store: store });
});
const { changeName, changeInfo } = newMutations;
</script>
  • 重要原则:执行的函数必须是同步函数
    • 这是因为 devtool 工具会记录 mutation 的日记
    • 每一条 mutation 被记录,devtools 都需要捕捉到前一状态和后一状态的快照
    • 但是在 mutation 中执行异步操作,就无法追踪到数据的变化

十二、actions

  • 目的就是为了完成异步操作

  • 所有的修改都必须提交 mutation,包括 actions

  • Action类似于mutation,不同在于

    • Action提交的是 mutation,而不是直接变更状态
    • Action可以包含任意异步操作
  • 有一个非常重要的参数 context

    • context 是一个和 store 实例均有相同方法和属性的 context 对象
    • 可以从其中获取到commit方法来提交一个mutation,或者通过 context.state 和 context.getters 来获取 state 和getters
<template>
  <div class="home">
    <h2>home:{{ $store.state.counter }}</h2>
    <button @click="actionBtnClick">发起action</button>
  </div>
</template>
<script>
export default {
  methods: {
    actionBtnClick() {
      this.$store.dispatch("incrementAction");
    },
  },
};
</script>
<script setup>
import { useStore } from "vuex";
const store = useStore();
store.dispatch("incrementAction");
</script>
<style lang="less" scoped></style>

  actions: {
    incrementAction(context,payload) {
      console.log(context.commit);//用于提交mutation
      console.log(context.getters);//getters
      console.log(context.state);//state
      context.commit("increment",payload)
    }
  }
  mutations: {
    increment(state) {
      state.counter++;
    }
  },

十三、mapActions

  • 适合vue2
<template>
  <div class="home">
    <h2>home:{{ $store.state.counter }}</h2>
    <button @click="incrementAction">发起action</button>
  </div>
</template>
<script>
 import { mapActions } from "vuex";
 export default {
   methods: {
//     // incrementAction() {
//     //   this.$store.dispatch("incrementAction");
//     // },
     ...mapActions(["incrementAction"]),
   },
 };
</script>
<script setup>
import { useStore, mapActions } from "vuex";
const store = useStore();
const { incrementAction } = mapActions(["incrementAction"]);
// store.dispatch("incrementAction");
</script>
  • Action 通常是异步的,可以通过让action返回Promise,在 Promise 的 then 中来处理完成后的操作

十四、actions 中异步操作

  • 数据管理方式一

    • 将从服务器拿到的数据,在对应的页面组件进行管理
  • 数据管理方式二

    • 一个页面中的组件数据,抽取到 Vuex 中管理
    • 在 actions 中发送网络请求
    • async 异步函数:返回的一定是 promise
     async fetchHomeMulticatedAction(context) {
          // 1. 返回promise,给promise设置then
          // fetch("jjjj").then((res) => {
          //   res.json().then((data) => {
          //     console.log(data);
          //   });
          // });
          // 2. promise 的链式调用
          // fetch("jjjj")
          //   .then((res) => {
          //     return res.json();
          //   })
          //   .then((data) => {
          //     console.log(data);
          //   });
    
          // 3. await/async
          const res = await fetch("http://");
          const data = await res.json()
          console.log(data);
          // 修改state的数据
          context.commit("changeBanner",data.data.banner.list)
        },
    
    <script setup>
    import { useStore } from "vuex";
    
    // 告诉 vuex 发送网络请求
    const store = useStore();
    store.dispatch("fetchHomeMulticatedAction");
    </script>
    

十五、modules

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

  • 为了解决以上问题,Vuex 可以将 store 分割成模块(module)

  • 每个模块拥有自己的 state、mutation、action、getter、甚至是嵌套子模块

  • 创建模块 modules/home.js ,在模板中使用需要加上模块名字

  • 模块内的 getter 里面的函数默认会合并到总的 store 里面

  • store中创建 modules ==》counter.js

const counter = {
  state: () => ({
    count:99
  }),
  mutations: {
    increment(state) {
      state.counter++
    }
  },
  getters: {
    doubleCount(state, getters, rootState) {
      return state.count + rootState.counter
    }
  },
  actions: {
    incrementCountAction(context) {
      context.commit("increment")
    }
  }
}
  • 总的index.js
  modules: {
    home: homeModule,
    counter:counterModule
  }
  • 使用
<template>
  <div class="home">
    <h2>home</h2>
    <!-- 使用state时,是需要state.moduleName.xxx -->
    <h2>counter模块的counter:{{ $store.state.counter.count }}</h2>
    <!-- 使用getters时,是直接getters.xxx -->
    <h2>counter模块的doubleCounter:{{ $store.getters.doubleCount }}</h2>
    <button @click="incrementCountAction">counter模块+1</button>
  </div>
</template>

<script setup>
import { useStore } from "vuex";

// 派发事件时候,也是不需要跟模块的
// 提交mutation时,也是不需要跟模块的,直接提交即可
const store = useStore();
function incrementCountAction() {
  store.dispatch("incrementCountAction");
}
</script>
<style lang="less" scoped></style>

十六、Module 的命名空间

  • 模块内部的 action 和 mutation 仍然是注册在全局的命名空间中的
    • 这样使得多个模块能够对同一个 action 或 mutation 作出响应
    • Getter 同样也默认注册在全局命名空间
  • 希望模块具有更高的封装度和复用性,可以添加 namespaced: true 的方式使其成为带命名空间的模块
    • 当模块被注册后,它的所有 getter、action 及 mutation 都会自动根据模块注册的路径调整命名
    • 使用
      • 模板中使用:{{$store.getters["counter/doubleCount"]}}
      • 派发事件:store.dispatch("counter/incrementAciton")
  • 17
    点赞
  • 20
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值