Vuex

vuex 全局状态管理器

Vuex 是一个专为 Vue.js 应用程序开发的状态管理模式,集中式存储管理应用的所有组件的状态

单向数据流

在这里插入图片描述

  • state,驱动应用的数据源;

  • view,以声明方式将 state 映射到视图;

  • actions,响应在view上的用户输入导致的状态变化

在这里插入图片描述

Vuex 的核心: store(仓库)

store中的状态是响应式的,在组件中调用 store 中的状态仅需要在计算属性中返回即可。触发变化也是在组件的 methods 中提交 mutation。

store.commit 方法触发状态变更

mutations

mutations接收两个参数 (state,payload)

向 store.commit 传入额外的参数,即 mutation 的 载荷(payload)

mapState 辅助函数

解决:组件获取多个状态,状态都声明为计算属性重复和冗余的问题

数组形式 可以直接把 state 中的 属性映射到 computed 中

对象形式 可以为映射之后的值设置一个属性名

在单独构建的版本中辅助函数为 Vuex.mapState

…mapState(扩展运算符) 函数返回的是一个对象

先引入:import { mapState } from ‘vuex’

 computed:{
    ...mapState(["count","msg"]), //可以直接把state中的count映射为计算属性中的count
    ...mapState({
      c:"count"    //// 可以为映射之后的值设置一个属性名
    })
  }

mapMutations 辅助函数

mapMutations可以把vuex中的mutations映射为methods

数组形式 可以直接把 mutations 中的 方法 映射映射到 methods 中

对象形式 可以为映射之后的值设置一个属性名

clickHandle() {
      this.$store.commit("addByStep", { step: 5 });
    },
    ...mapMutations(["addByStep", "reduceByStep"]),
    ...mapMutations({
      a: "addByStep"
    })
  }

Action 异步操作

所有的异步操作都放在这里, 通过dispatch触发一个actions
接受两个参数: context payload
context 当前的上下文store对象
payload 表示传递的参数

actions: {
    /**
     *
     * @param {*} context   当前的上下文store对象
     * @param {*} payload   表示传递的参数
     */
    loadPosts({ commit }, payload) {
      // console.log(context);
      // console.log(payload);
      // commit('loadDataEnd', ['一', '二', '三']);
      axios.get('http://jsonplaceholder.typicode.com/posts').then(res => {
        commit('loadDataEnd', res.data);
      });
    },
  },

mapActions可以把actions映射成methods

使用命名空间把数据进行映射

import { mapActions, mapState } from "vuex";

 methods: {
    ...mapActions(["loadPosts"]),
    // 使用命名空间把数据进行映射
    ...mapActions("product", {
      loadProducts: "loadData"
    }),
    loadMore() {
      this.loadProducts({
        page: this.currentPage
      });
      this.currentPage += 1;
    }
  },

modules

通过modules实现vuex的模块化拆分,可以把状态树按照功能拆分成小文件

namespaced: true, 为当前模块提供命名空间
当我们使用了 modules 和 nameapaced 之后,在触发 action 的时候需要加上命名空间前缀,使用命名空间之后可以把数据和 actions 以及 mutations 等内容做一个独立处理,防止数据串联

 modules:{
    product:{
      namespaced:true,
      state:{
        list:[],
        page:1,
        totalPages:1
      },
       mutations:{
        loadDataEnd(state,payload){
          console.log(state)
          console.log(payload)
        }
      },
      actions:{
        loadData({commit}){
          commit('loadDataEnd',{
            msg:'天气阴晴不定...'
          })
        }
      }
    },
    cart:{
      namespaced:true,
      state:{
        list:[]
      }
    },
    user:{
      namespaced:true,
      state:{
        info:{}
      }
    },
  }



可以直接调用actions 
 <button @click="$store.dispatch('product/loadData')">获取商品信息</button>
 methods: {
    ...mapActions(["loadPosts"]),
    // 使用命名空间把数据进行映射
    ...mapActions("product", {
      loadProducts: "loadData"
    }),
   }
  ``
### Vuex 的核心概念与使用方法 Vuex 是专门为 Vue.js 设计的一个状态管理模式,用于集中管理应用中的状态。通过 Vuex,可以更方便地处理组件间的全局状态以及复杂的组件间通信。 #### 1. 安装与初始化 在项目中引入 Vuex 需要先安装依赖包 `vuex` 并将其注册为 Vue 插件[^1]: ```javascript import Vue from 'vue'; import Vuex from 'vuex'; Vue.use(Vuex); const store = new Vuex.Store({ state: { count: 0, }, mutations: {}, actions: {}, getters: {} }); export default store; ``` #### 2. 创建简单的 Vuex Store 创建一个基本的 Vuex Store 可以定义四个主要部分:`state`, `mutations`, `actions`, 和 `getters`[^1]。下面是一个完整的简单示例: ```javascript // store/index.js import Vue from 'vue'; import Vuex from 'vuex'; Vue.use(Vuex); export default new Vuex.Store({ state: { // 存储数据的地方 count: 0, }, mutations: { // 同步修改 state 的唯一方式 increment(state) { state.count++; } }, actions: { // 提交 mutation 的地方,支持异步操作 incrementAsync({ commit }) { setTimeout(() => { commit('increment'); }, 1000); } }, getters: { // 访问经过计算后的 state 数据 doubleCount(state) { return state.count * 2; } } }); ``` #### 3. 模块化组织状态 对于较大的应用程序,推荐将 Vuex Store 划分为模块来提高可维护性和清晰度[^2]。每个模块都可以拥有自己的 `state`, `mutations`, `actions`, 和 `getters`: ```javascript // store/modules/exampleModule.js const exampleModule = { namespaced: true, // 开启命名空间 state() { return { text: 'Hello Vuex Module', }; }, mutations: { updateText(state, newText) { state.text = newText; } }, actions: { changeText({ commit }, payload) { commit('updateText', payload); } }, getters: { getText(state) { return state.text.toUpperCase(); } } }; export default exampleModule; // store/index.js import Vue from 'vue'; import Vuex from 'vuex'; import exampleModule from './modules/exampleModule'; Vue.use(Vuex); export default new Vuex.Store({ modules: { example: exampleModule } }); ``` #### 4. 状态持久化 为了防止页面刷新丢失状态,可以通过插件 `vuex-persistedstate` 将 Vuex 中的状态保存到浏览器的本地存储中[^3]: ```bash npm install vuex-persistedstate ``` 配置如下所示: ```javascript // store/index.js import createPersistedState from 'vuex-persistedstate'; import Vue from 'vue'; import Vuex from 'vuex'; Vue.use(Vuex); export default new Vuex.Store({ state: { user: null, }, plugins: [ createPersistedState() ] }); ``` #### 5. Vuex 常见问题解答 - **何时应该使用 Vuex?** 当存在多组件共享状态、组件间通信复杂或者需要多个视图监听同一状态变化时,建议采用 Vuex 来统一管理和分发这些状态[^3]。 - **如何与 Vue Router 结合使用?** 可以在路由守卫中调用 Vuex 的 action 方法完成权限校验或其他逻辑处理[^3]: ```javascript router.beforeEach((to, from, next) => { if (to.meta.requiresAuth && !store.getters.isAuthenticated) { next('/login'); // 如果未登录则跳转至登录页 } else { next(); // 继续导航 } }); ``` --- ###
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值