每天学习一点vue知识(九)

1.对vuex的个人理解

​ Vuex 是 Vue.js 应⽤程序状态管理的官⽅库,⽤于集中管理应⽤程序的所有组件的状态。主要包括以下
​ ⼏个核⼼概念:
State(状态): 存储应⽤程序级别的状态,是响应式的。
Getters(获取器): ⽤于从状态中派⽣出⼀些新的状态,类似于计算属性。
Mutations(突变): ⽤于修改状态,必须是同步函数。
Actions(动作): ⽤于异步操作,可以包含任意异步操作,然后提交 mutations。
Modules(模块): 允许将 store 分割成模块,每个模块有⾃⼰的 state、getters、mutations、
​ actions。
​ Vuex 的核⼼思想是通过⼀个全局的状态管理仓库来管理组件的状态,使得状态变化更加可追踪、可维
​ 护。

2.如何监听vuex中数据的变化

​ 在 Vuex 中监听数据变化通常使用 Vuex 提供的 watch 函数或者在组件中使用计算属性(computed)来实现。下面是两种方法的示例:

使用 Vuex 提供的 watch 函数:

   import { watch } from 'vuex';

    // 假设 store 是你的 Vuex store 实例
    watch(
      () => store.state.yourModule.yourData, // 监听的数据路径
      (newValue, oldValue) => {
        // 当数据变化时执行的回调函数
        console.log('数据变化了!新值为:', newValue, '旧值为:', oldValue);
        // 在这里可以执行其他操作,例如更新组件中的数据或触发其他逻辑
      }
    );

在组件中使用计算属性(computed):

  export default {
      computed: {
        // 假设 'yourData' 是你在 Vuex store 中的状态
        yourData() {
          return this.$store.state.yourModule.yourData;
        }
      },
      watch: {
        // 监听计算属性的变化
        yourData(newValue, oldValue) {
          // 当数据变化时执行的回调函数
          console.log('数据变化了!新值为:', newValue, '旧值为:', oldValue);
          // 在这里可以执行其他操作,例如更新组件中的数据或触发其他逻辑
        }
      }
    };

3.页面刷新后vuex的数据丢失如何解决

​ 解决页面刷新后 Vuex 数据丢失的问题通常需要结合浏览器本地存储来实现持久化。你可以使用浏览器的本地存储机制(如 localStorage 或 sessionStorage)将 Vuex 数据存储在客户端,以便在页面刷新后恢复数据。

​ 下面是一种解决方案的示例:

   // 在 Vuex store 中设置一个 action,在页面加载时从本地存储中读取数据并初始化 Vuex 状态
    const store = new Vuex.Store({
      state: {
        // 初始状态
        yourData: null
      },
      mutations: {
        // 更新状态的 mutation
        updateYourData(state, newData) {
          state.yourData = newData;
        }
      },
      actions: {
        // 从本地存储加载数据的 action
        loadFromLocalStorage(context) {
          const savedData = localStorage.getItem('yourData');
          if (savedData) {
            context.commit('updateYourData', JSON.parse(savedData));
          }
        }
      }
    });

    // 在页面加载时调用该 action
    store.dispatch('loadFromLocalStorage');

    // 监听 Vuex 中数据的变化,并将数据存储到本地存储中
    store.watch(
      (state) => state.yourData,
      (newValue) => {
        localStorage.setItem('yourData', JSON.stringify(newValue));
      },
      { deep: true }
    );

​ 在这个示例中:

​ Vuex store 中的 loadFromLocalStorage action 在页面加载时从本地存储中读取数据,并通过 mutation 更新 Vuex 的状态。
​ 监听 Vuex 中数据的变化,当数据发生变化时将数据存储到本地存储中。
​ 这样,在页面刷新后,通过 loadFromLocalStorage action 可以将数据从本地存储中恢复到 Vuex 状态中。

4.mutation和action的区别

​ Mutation 和 Action 是 Vuex 中用于管理状态的两个核心概念,它们之间有以下区别:

Mutation(变更)
​ 用途:Mutation 用于同步地修改 Vuex 的状态,是唯一能够修改 Vuex 状态的地方。
​ 触发方式:通过提交(commit)Mutation 来触发。
​ 示例:Mutation 是一些包含对状态进行更改的函数,例如更新某个数据字段的值。
​ 语法:通常在 Vuex store 中定义为一个名为 mutations 的对象,其中包含一系列的 Mutation 函数。

  const store = new Vuex.Store({
      state: {
        count: 0
      },
      mutations: {
        increment(state) {
          state.count++;
        },
        decrement(state) {
          state.count--;
        }
      }
    });

Action(动作)
​ 用途:Action 用于封装异步逻辑或者复杂的业务逻辑,可以包含任意异步操作
​ 触发方式:通过派发(dispatch)Action 来触发。
​ 示例:Action 可以包含异步的 API 调用、条件判断、甚至是多个 Mutation 的触发等复杂逻辑。
​ 语法:通常在 Vuex store 中定义为一个名为 actions 的对象,其中包含一系列的 Action 函数。

  const store = new Vuex.Store({
      state: {
        count: 0
      },
      mutations: {
        increment(state) {
          state.count++;
        },
        decrement(state) {
          state.count--;
        }
      },
      actions: {
        asyncIncrement(context) {
          setTimeout(() => {
            context.commit('increment');
          }, 1000);
        }
      }
    });
区别总结:

同步 vs 异步:Mutation 是同步的操作,而 Action 可以是异步的。
直接 vs 间接修改状态:Mutation 直接修改状态,而 Action 通过 Mutation 间接修改状态。
触发方式:Mutation 通过提交来触发,Action 通过派发来触发。
适用场景:通常情况下,Mutation 用于同步的状态修改,而 Action 用于异步的操作、复杂的逻辑处理等。

5.vuex中的module

​ 在 Vuex 中,module 是用于将 Store 分割成模块的概念。模块可以包含自己的 state、mutations、actions、getters 等,并且可以嵌套使用,使得 Vuex 应用程序更易于管理和维护。

使用 Module 的优势
​ **命名空间:**模块可以拥有自己的命名空间,这意味着模块内部的 mutations、actions、getters 等不会与其他模块发生冲突,可以避免命名冲突问题。

​ **代码组织:**将相关功能的状态管理逻辑放在一个模块中,可以更好地组织代码,提高代码的可读性和可维护性。

​ **复用性:**模块可以被其他模块引用和重复使用,使得 Vuex 中的状态管理逻辑更具有复用性。

​ 示例:
​ 下面是一个简单的示例,演示了如何在 Vuex 中使用 Module:

 import { createStore } from 'vuex';

    // 定义一个模块
    const counterModule = {
      state: {
        count: 0
      },
      mutations: {
        increment(state) {
          state.count++;
        },
        decrement(state) {
          state.count--;
        }
      },
      actions: {
        asyncIncrement(context) {
          setTimeout(() => {
            context.commit('increment');
          }, 1000);
        }
      },
      getters: {
        doubleCount(state) {
          return state.count * 2;
        }
      }
    };
    // 创建 Vuex Store,并将模块注册到 Store 中
    const store = createStore({
      modules: {
        counter: counterModule // 将 counterModule 注册为名为 "counter" 的模块
      }
    });

    // 在组件中使用模块中的状态、mutations、actions 和 getters
    export default {
      computed: {
        count() {
          return this.$store.state.counter.count; // 访问模块中的 state
        },
        doubleCount() {
          return this.$store.getters['counter/doubleCount']; // 访问模块中的 getter
        }
      },
      methods: {
        increment() {
          this.$store.commit('counter/increment'); // 调用模块中的 mutation
        },
        asyncIncrement() {
          this.$store.dispatch('counter/asyncIncrement'); // 调用模块中的 action
        }
      }
    };

​ 在这个示例中,我们创建了一个名为 “counter” 的模块,并在 Vuex Store 中注册了该模块。然后在组件中就可以通过 this. s t o r e . s t a t e . c o u n t e r 访问模块的状态,通过 t h i s . store.state.counter 访问模块的状态,通过 this. store.state.counter访问模块的状态,通过this.store.commit(‘counter/increment’) 调用模块的 mutation,通过 this. s t o r e . d i s p a t c h ( ′ c o u n t e r / a s y n c I n c r e m e n t ′ ) 调用模块的 a c t i o n ,以及通过 t h i s . store.dispatch('counter/asyncIncrement') 调用模块的 action,以及通过 this. store.dispatch(counter/asyncIncrement)调用模块的action,以及通过this.store.getters[‘counter/doubleCount’] 访问模块的 getter。

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值