vuex的使用

本文概述了在Vue应用中如何使用Vuex进行数据共享与组件间通信,包括state、mutations、actions和getters的使用及其作用,以及模块化的最佳实践。

vue中

少量数据共享,父传子用属性绑定,子传父用的是事件绑定,兄弟传值需要借助evetbus

大量数据共享需要使用vuex,本质上是一个状态管理工具,可以看成是一个仓库,主要功能是数据共享和组件通信。

主要包括五种属性

state:用于存放共享数据,直接使用时采用this.$store.state.DateName调用

mutations:用于存放修改共享数据的方法,mutations中定义同步任务,使用时,通过在methods中添加函数,在函数使用this.$store.commit("MethodName")

actions:用于存放异步任务,需要间接触发mutations实现state数据的改变,在mutations中添加数据修改方法,在actions中添加异步操作,并用context.commit("MethodName")触发mutations操作,在methods中添加函数,在函数使用this.$store.dispatch("AsyncMethodName")

getters:用于存放计算属性,使用时通过this.$store.getters.MethodName

modules:用于将store拆分成小模块,每个模块都有自己的state,mutations,actions,getters
注意

  • 1. 应用层级的状态都应该集中在store中

  • 2. 提交 mutation 是更改状态state的唯一方式,并且这个过程是同步的。

  • 3. 异步的操作应该都放在action里面

基本步骤

1.先导入vue,再导入vuex

2.创建vuex对象

const store=new Vuex.Store({...})

3.在父组件中添加store:store,父组件和其所有的子组件都可以使用

state

state用于保存共享数据

注意:

直接使用时采用this.$store.state.DateName调用

<div>{{this.$store.state.msg}}</div>
const store=new Vuex.Store({
    state:{
        msg:0;
    }
})

mutations

不推荐在组件中直接修改共享数据,如果多个组件都修改了共享数据,那么后期数据发生了错误,如果我们需要调试错误就需要吧每一个修改共享数据的组件都检查一遍

mutations用于保存修改共享数据的方法

注意:

1.mutations中定义的方法传参为state,可以通过state获得共享数据

2.使用时通过在method中添加函数,在函数使用this.$store.commit("MethodName")

3.第二种方式时引入mapMutations函数,对mutations中的方法做一个映射

<div @click="add()"> </div>
const store=new Vuex.Store({
    state:{
        msg:0;
    },
    mutations:{
        mAdd(state){
        state.msg++
        }
})
methods:{
    add(){
    this.$store.commit("mAdd");
    }
}

有参数时

const store=new Vuex.Store({
    state:{
        msg:0;
    },
    mutations:{
        mAdd(state,step){
        state.msg=state.msg+step
        }
})
methods:{
    add(){
    this.$store.commit("mAdd",3);
    }
}

actions

mutations中不能执行异步操作,不能触发state数据的修改,页面上展示的会被修改

actions用于触发异步任务,action中也需要间接触发mutations改变数据

actions不能修改state,只有mutation可以,因此需要间接触发mutations

注意:

1.需要在mutations中添加同步方法

2.在actions中添加异步方法,接受的参数为context,利用context.commit("MethodName")触发同步操作

3.使用时通过在method中添加函数,在函数使用this.$store.dispatch("AsyncMethodName")

4.第二种可以通过mapActions函数触发actions,映射为methods方法

const store=new Vuex.Store({
    state:{
        msg:0;
    },
    mutations:{
        mAdd(state){
            state.msg++
        }
    },
    getters:{
    },
    actions:{
        addAsync(context){
            setTimeout(()=>{
                context.commit('mAdd')
            })
        }
    }

})
methods:{
    add(){
    this.$store.dispatch('addAsync');
    }
}

携带参数时

const store=new Vuex.Store({
    state:{
        msg:0;
    },
    mutations:{
        mAdd(state,step){
            state.msg+=step
        }
    },
    getters:{
    },
    actions:{
        addAsync(context){
            setTimeout(()=>{
                context.commit('mAdd',step)
            })
        }
    }

})
methods:{
    add(){
    this.$store.dispatch('addAsync',3);
    }
}

 getters

getters用于保存计算属性,计算属性会被缓存,多次使用只执行一次

数据在data中则使用computed计算,数据在state中则使用getter计算

注意:

1.getters中定义的方法传参为state,可以通过state获得共享数据

2.使用时通过this.$store.getters.MethodName

<div>{{this.$store.getters.formate}}</div>
const store=new Vuex.Store({
    state:{
        msg:"Hello World";
    },
    mutations:{
    },
    getters:{
        formate(state){
            return state.msg+"Hello Bourbon"
        }
    }

})

modules

modules用于将store拆分成小模块

每个模块都有自己的state,mutations,actions,getters

const moduleA = {
    state: {...},
    getters: {...},
    mutations: {....},
  actions: {...}
}
 
const moduleB = {
    state: {...},
    getters: {...},
    mutations: {....},
  actions: {...}
}
 
const store = new Vuex.Store({
  modules: {
    a: moduleA,
    b: moduleB
  }
});
 
store.state.a // 获取moduleA的状态
store.state.b // 获取moduleB的状态

### Vuex 使用指南及实现状态管理示例 Vuex 是一个专为 Vue.js 应用设计的状态管理库,它采用集中式存储管理应用的所有组件的状态,并以相应的规则保证状态以一种可预测的方式发生变化[^1]。以下是关于 Vuex 的核心概念和使用方法的详细说明。 #### 1. 核心概念 Vuex 的核心概念包括以下几个部分: - **State**:用于存储共享的状态数据。 - **Getter**:类似于 Vue 组件中的计算属性,用于从 state 中派生出一些状态。 - **Mutation**:用于同步地修改 state 的方法。 - **Action**:类似于 mutation,但可以包含异步操作,最终会提交 mutation 来改变 state。 - **Module**:将 store 分割成模块,使代码更易于维护。 #### 2. 创建 Vuex Store 在项目中创建一个 `store.js` 文件,定义 Vuex 的 store: ```javascript // store.js import Vue from 'vue'; import Vuex from 'vuex'; Vue.use(Vuex); export default new Vuex.Store({ state: { count: 0 // 示例状态 }, getters: { doubleCount(state) { return state.count * 2; // 计算属性示例 } }, mutations: { increment(state) { state.count++; // 同步修改状态 } }, actions: { incrementAsync({ commit }) { setTimeout(() => { commit('increment'); // 异步操作后提交 mutation }, 1000); } } }); ``` #### 3.Vue 实例中引入 Store 在 `main.js` 文件中引入并挂载 store: ```javascript // main.js import Vue from 'vue'; import App from './App.vue'; import store from './store'; new Vue({ store, // 挂载 store render: h => h(App) }).$mount('#app'); ``` #### 4. 在组件中使用 Vuex 通过 `mapState`、`mapGetters`、`mapMutations` 和 `mapActions` 辅助函数简化对 Vuex 的访问: ```javascript <template> <div> <p>Count: {{ count }}</p> <p>Double Count: {{ doubleCount }}</p> <button @click="increment">Increment</button> <button @click="incrementAsync">Increment Async</button> </div> </template> <script> import { mapState, mapGetters, mapMutations, mapActions } from 'vuex'; export default { computed: { ...mapState(['count']), // 映射 state 到本地计算属性 ...mapGetters(['doubleCount']) // 映射 getter 到本地计算属性 }, methods: { ...mapMutations(['increment']), // 映射 mutation 到本地方法 ...mapActions(['incrementAsync']) // 映射 action 到本地方法 } }; </script> ``` #### 5. 状态持久化 未进行持久化配置可能导致状态丢失、数据不一致或重复操作等问题[^3]。可以通过插件如 `vuex-persistedstate` 实现状态持久化: ```javascript // store.js import createPersistedState from 'vuex-persistedstate'; export default new Vuex.Store({ state: { count: 0 }, plugins: [createPersistedState()] // 添加持久化插件 }); ``` 这样,即使页面刷新,状态也会被保存到 localStorage 或 sessionStorage 中。 ---
评论 1
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

每天都在掉头发

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值