vuex使用完整版

场景2需要在vuex中大量管理数据

定义文件和变量

文件设置,在src下添加如下的文件目录

--store

---actions.js

---getters.js

---index.js

---mutation-types.js

---mutations.js

---state.js

第一步设计state.js,这里面确定需要被vuex管理的变量

state.js

import {playMode} from '@/common/js/config.js'   //获取项目的配置---可选
const state={
  singer:{},
  playing:false,
  fullScreen:false,
  playList:[],
  sequenceList:[],
  mode:playMode.sequence,
  currentIndex:-1
};

export default state

第二步设置getters.js映射,也就是确定vuex中能够被取到的值

getters.js

export const singer= state => state.singer;         //简单点说就是把state.singer映射到常量singer上

export const playing= state => state.playing;

export const fullScreen= state => state.fullScreen;

export const playList= state => state.playList;

export const sequenceList= state => state.sequenceList;

export const mode= state => state.mode;

export const currentIndex= state => state.currentIndex;

export const currentSong = (state)=>{                        //getters同时承担了计算属性的功能,将state中的变量二次组装计算抛出新的变量让组件使用
  return state.playList[state.currentIndex] || {}
};

第三步定义如何修改vuex中的值,mutations和actions都可以修改,那么我们需要先定义mutation-type

mutation-type.js

export const SET_SINGER='SET_SINGER';                 //定义修改动作名称,也就是mutations中修改数据的方法名

export const SET_PLAYING_STATE='SET_PLAYING_STATE';

export const SET_FULL_SCREEN='SET_FULL_SCREEN';

export const SET_PLAYLIST='SET_PLAYLIST';

export const SET_SEQUENCE_LIST='SET_SEQUENCE_LIST';

export const SET_PLAY_MODE='SET_PLAY_MODE';

export const SET_CURRENT_INDEX='SET_CURRENT_INDEX';

第四步定义mutations,定义vuex中数据的修改方法

mutations.js

import * as types from './mutation-types'

const mututations={
  [types.SET_SINGER](state,singer) {
    state.singer=singer
  },
  [types.SET_PLAYING_STATE](state,flag){
    state.playing=flag
  },
  [types.SET_FULL_SCREEN](state,flag){
    state.fullScreen=flag
  },
  [types.SET_PLAYLIST](state,list){
    state.playList=list
  },
  [types.SET_SEQUENCE_LIST](state,list){
    state.sequenceList=list
  },
  [types.SET_PLAY_MODE](state,mode){
    state.mode=mode
  },
  [types.SET_CURRENT_INDEX](state,index){
    state.currentIndex=index
  }
};

export default mututations;

第五步定义action----mutation通常是每个方法修改单个值,而action通常是每个方法同时修改多个值,action中还会做些异处理---这里经常是根据业务逻辑写方法,一般是之后边开发边写,开始的时候不需要定义

action.js

import * as types from './mutation-types'  
export const selectPlay=function ({commit,state},{list,index}) {    //selectPlay一个方法执行多个commit
  commit(types.SET_PLAYLIST,list);
  commit(types.SET_SEQUENCE_LIST,list);
  commit(types.SET_CURRENT_INDEX,index);
  commit(types.SET_FULL_SCREEN,true);
  commit(types.SET_PLAYING_STATE,true);
};

第六部注册,所有的文件定义好了,就可以注册了

index.js

import Vue from 'vue'
import Vuex from 'vuex'
import * as actions from './actions'
import * as getters from  './getters'
import  state from './state'
import  mutations from './mutations'
import createLogger from 'vuex/dist/logger'    //辅助调试插件引入,在vuex中的值发生改变的时候会自动在控制台打出变量改变前后的值
Vue.use(Vuex);

const debug= process.env.NODE_ENV != 'production'

export default new Vuex.Store({
  actions,
  getters,
  state,
  mutations,
  strict:debug,
  plugins:debug?[createLogger()]:[]         //让调试插件只在开发时开启
})

在main,js中

import store from './store'    //本质上是引入index.js
new Vue({
    el: '#app',
    router,
    store,                                           //store实例注册到vue实例中
    render: h => h(App)
})

使用vuex中的变量

1getter---获取vuex中的变量并使用

import {mapGetters} from 'vuex';
computed:{
 ...mapGetters([  //获取暴露出vuex中的变量,这里暴露出来的变量直接当计算属性使用
    'fullScreen',
    'playList',
    'currentSong',
    'playing'
  ]), 
},

2mutation--修改vuex中的某个值

import {mapMutations} from 'vuex';
methods:{
  setFullScreen(){
      this.setFullScreen(true); //直接调用方法提交修改vuex中的变量
  },
    stopPlay(){
        this.setPlayingState(false);
    },
    ...mapMutations( //不能直接修改vuex中的变量,通过映射方法传参数的方式提交改变vuex中的参数
        {
            setFullScreen:'SET_FULL_SCREEN',
            setPlayingState:'SET_PLAYING_STATE'
        }
    )
},

 

3action---使用actions.js中的方法改变vuex中的变量

import {mapActions} from 'vuex'  //action中定义一次改变vuex中多个变量的方法
methods:{
  selectItem(song,index){
    this.selectPlay({   //直接调用并传入需要的参数
      list:this.songs,
      index:index
    })
  },
  ...mapActions([  //暴露出actions中的方法,作为方法直接调用
    'selectPlay'
  ])
},

简易版查看:https://blog.youkuaiyun.com/github_39274378/article/details/81542554

<think>好的,用户问的是“vuex 如何使用”,我需要详细回答这个问题。首先,用户可能是在开发Vue 2项目,因为Vuex是Vue 2的官方状态管理库,而Vue 3推荐使用Pinia。不过也有可能用户还在维护旧项目,所以需要讲解Vuex的基本用法。 首先,我应该从Vuex的核心概念入手,比如State、Getter、Mutation、Action、Module。然后给出一个简单的示例,让用户能快速上手。可能还需要说明如何在组件中使用这些部分,比如mapState、mapActions等辅助函数。 接下来,用户可能需要了解如何组织代码结构,比如store.js的位置和模块化的做法。还要注意Vue 2和Vue 3使用Vuex的不同之处,不过用户的问题可能更偏向Vue 2,因为Vue 3建议用Pinia。不过还是需要提一下兼容性。 另外,用户可能遇到常见问题,比如状态更新不生效,这时候需要提醒使用Mutation来修改状态,或者在异步操作中使用Action。还有模块化的使用场景,以及如何通过辅助函数简化代码。 还要考虑用户可能的误区,比如直接在组件中修改state,而没有使用Mutation,导致状态管理混乱。这时候需要强调最佳实践,确保状态变更可追踪。 最后,总结Vuex使用步骤,并给出相关问题,比如与Pinia的区别,模块化管理,异步操作处理等。确保回答全面,覆盖用户可能关心的各个方面。 </think>Vuex 是 Vue 2 的官方状态管理库,用于集中管理组件间的共享状态。以下是 **Vuex 的核心概念和使用方法**,适用于 Vue 2 项目。 --- ### ✅ 1. **安装与初始化** #### (1) 安装 Vuex ```bash npm install vuex@next --save # Vue 3 兼容版本 # 或 Vue 2 专用版本 npm install vuex@3 --save ``` #### (2) 创建 `store.js` 通常放在 `src/store/index.js`: ```javascript // src/store/index.js import Vue from 'vue'; import Vuex from 'vuex'; Vue.use(Vuex); // 必须通过 Vue.use() 安装插件 export default new Vuex.Store({ state: {}, // 状态(数据源) getters: {}, // 派生状态(类似计算属性) mutations: {}, // 同步修改状态的方法 actions: {}, // 异步操作(如接口请求) modules: {} // 模块化拆分 }); ``` #### (3) 挂载到 Vue 应用 ```javascript // main.js import Vue from 'vue'; import App from './App.vue'; import store from './store'; // 引入 store new Vue({ store, // 挂载到根实例 render: h => h(App) }).$mount('#app'); ``` --- ### ✅ 2. **核心概念详解** #### (1) **State**(状态) 存储共享数据: ```javascript // store.js state: { count: 0, user: { name: 'Alice', role: 'admin' } } ``` **组件中使用:** ```vue <template> <p>当前计数:{{ $store.state.count }}</p> </template> ``` #### (2) **Getter**(派生状态) 类似计算属性,用于处理状态: ```javascript getters: { doubleCount: state => state.count * 2, isAdmin: state => state.user.role === 'admin' } ``` **组件中使用:** ```vue <template> <p>双倍计数:{{ $store.getters.doubleCount }}</p> </template> ``` #### (3) **Mutation**(同步修改状态) 必须通过 `commit` 调用: ```javascript mutations: { increment(state) { state.count++; }, updateRole(state, newRole) { state.user.role = newRole; } } ``` **组件中调用:** ```javascript this.$store.commit('increment'); this.$store.commit('updateRole', 'guest'); ``` #### (4) **Action**(异步操作) 用于处理异步逻辑(如接口请求): ```javascript actions: { async fetchUser({ commit }) { const res = await fetch('/api/user'); commit('updateRole', res.data.role); } } ``` **组件中调用:** ```javascript this.$store.dispatch('fetchUser'); ``` #### (5) **Module**(模块化拆分) 当状态复杂时,拆分为模块: ```bash src/store/ ├── modules/ │ ├── userModule.js │ └── cartModule.js └── index.js ``` **模块定义示例:** ```javascript // src/store/modules/userModule.js export default { namespaced: true, // 启用命名空间 state: { user: {} }, mutations: { setUser(state, user) { state.user = user; } } } ``` **在根 Store 中注册:** ```javascript // src/store/index.js import userModule from './modules/userModule'; export default new Vuex.Store({ modules: { user: userModule } }); ``` **组件中调用模块:** ```javascript this.$store.commit('user/setUser', { name: 'Bob' }); ``` --- ### ✅ 3. **辅助函数简化代码** Vuex 提供 `mapState`、`mapGetters`、`mapMutations`、`mapActions` 简化操作。 #### (1) **mapState** ```javascript import { mapState } from 'vuex'; export default { computed: { ...mapState(['count', 'user']) // 映射为计算属性 } } ``` **模板中使用:** ```vue <p>计数:{{ count }}</p> ``` #### (2) **mapGetters** ```javascript import { mapGetters } from 'vuex'; computed: { ...mapGetters(['doubleCount', 'isAdmin']) } ``` #### (3) **mapMutations** ```javascript import { mapMutations } from 'vuex'; methods: { ...mapMutations(['increment', 'updateRole']) } ``` **调用:** ```javascript this.increment(); // 直接调用 ``` #### (4) **mapActions** ```javascript import { mapActions } from 'vuex'; methods: { ...mapActions(['fetchUser']) } ``` --- ### ✅ 4. **完整示例** #### (1) Store 定义 ```javascript // src/store/index.js import Vue from 'vue'; import Vuex from 'vuex'; Vue.use(Vuex); export default new Vuex.Store({ state: { count: 0 }, mutations: { increment(state) { state.count++; } }, actions: { incrementAsync({ commit }) { setTimeout(() => commit('increment'), 1000); } }, getters: { doubleCount: state => state.count * 2 } }); ``` #### (2) 组件使用 ```vue <template> <div> <p>当前计数:{{ count }}</p> <p>双倍计数:{{ doubleCount }}</p> <button @click="increment">+1</button> <button @click="incrementAsync">异步+1</button> </div> </template> <script> import { mapState, mapGetters, mapMutations, mapActions } from 'vuex'; export default { computed: { ...mapState(['count']), ...mapGetters(['doubleCount']) }, methods: { ...mapMutations(['increment']), ...mapActions(['incrementAsync']) } }; </script> ``` --- ### ✅ 5. **常见问题** | 问题 | 原因 | 解决方案 | |------|------|----------| | 状态未更新 | 直接修改 `state` 而未使用 `mutation` | 通过 `commit` 调用 mutation | | 异步操作失败 | 在 `mutation` 中执行异步逻辑 | 将异步逻辑移到 `action` 中 | | 模块未生效 | 未启用 `namespaced: true` | 启用命名空间并使用路径调用 | | 辅助函数报错 | 未正确展开 `...mapXXX` | 确保使用 `...` 展开运算符 | --- ### ✅ 6. **Vue 3 中使用 Vuex** Vue 3 推荐使用 **Pinia**,但若需兼容 Vue 3,可使用 `vuex@next`: ```bash npm install vuex@next --save ``` **挂载方式:** ```javascript // main.js (Vue 3) import { createApp } from 'vue'; import { createStore } from 'vuex'; import App from './App.vue'; const store = createStore({ /* Vuex 配置 */ }); const app = createApp(App); app.use(store); app.mount('#app'); ``` --- ### ✅ 7. **总结** | 概念 | 作用 | 调用方式 | |------|------|----------| | `state` | 存储数据 | `this.$store.state.xxx` | | `getter` | 派生计算属性 | `this.$store.getters.xxx` | | `mutation` | 同步修改状态 | `this.$store.commit('type', payload)` | | `action` | 异步操作 | `this.$store.dispatch('type', payload)` | | `module` | 模块化拆分 | `this.$store.commit('moduleName/type', payload)` | --- ###
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值