vuex的安装和基本使用

什么是vuex

Vuex 是一个专为 Vue.js 应用程序开发的状态管理模式。它采用集中式存储应用的所有组件的状态,并以相应的规则保证状态以一种可预测的方式发生变化。简单来说,当你的 Vue 应用存在多个组件共享状态(如用户登录状态、购物车商品信息等)时,使用 Vuex 可以更方便地管理这些状态,避免组件之间复杂的状态传递。

安装和配置

在安装的时候需要注意的点是:vue3版本通常使用vuex4,vue2版本通常使用vuex3。这两个版本在配置和使用上有一些区别。

在项目package.json文件中可以查看当前版本,这里使用vue3,vuex4。当然也可以在这里查看新增的依赖是否安装成功,或者使用命令 

//npm list 可以列出项目中安装的所有依赖项及其版本信息
npm list vuex
  "dependencies": {
    "core-js": "^3.8.3",
    "router": "^1.3.8",
    "vue": "^3.2.13",
    "vuex": "^4.1.0"
  },

安装命令 

如果是vue3,直接执行以下命令会默认安装最新版本的vuex

npm i vuex   

如果vue2,需要声明下vuex版本

npm install vuex@3
//也可以指定版本号 比如
npm install vuex@3.6.2

vue3+vuex4

首先在src文件夹下,创建store文件夹,在创建index.js

import { createStore } from 'vuex'

// 创建 store 实例
const store = createStore({
    // 状态,用于存储应用的共享数据
    state() {
        return {
            count: 0
        }
    },
    // 获取器,类似于计算属性,用于获取 state 中的数据
    getters: {
        getCount(state) {
            return state.count
        }
    },
    // 突变,用于修改 state 中的数据,必须是同步操作
    mutations: {
        increment(state) {
            state.count++
        },
        decrement(state) {
            state.count--
        }
    },
    // 动作,用于处理异步操作,最终会触发 mutations 来修改 state
    actions: {
        incrementAsync(context) {
            setTimeout(() => {
                context.commit('increment')
            }, 1000)
        }
    }
})
export default store

配置main.js文件

import { createApp } from 'vue'
import App from './App.vue'
//引入刚才创建的文件,此文件封装了应用的状态管理逻辑
import store from './store'

const app = createApp(App);
console.log('app', app);
/**
 * 使用 Vuex 的 store 实例。
 * 在 Vue 3 中,通过 app.use() 方法来安装插件或注册全局的功能。
 * 这里传入的 store 是 Vuex 创建的状态管理实例,它包含了应用的状态、突变、动作等。
 * 调用 app.use(store) 后,整个 Vue 应用都会具备访问 store 中状态和方法的能力。
 * 例如,在组件中可以通过 this.$store (选项式 API)或 useStore() 组合式函数来访问 store。
 */
app.use(store);
app.mount('#app')

使用

<template>
  <div id="app">
      <p>Count: {{ count }}</p>
      <button @click="increment">加1</button>
      <button @click="decrement">减1</button>
      <button @click="incrementAsync">异步操作,1秒后加1</button>
  </div>
</template>

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

const store = useStore()
// 这里打印store,可以看到常用的方法 getters,commit,dispatch
// store打印图片会贴在该模块总结位置
console.log('store',store);

// 获取 state 中的 count 值  有两种方式
// 第一种通过计算属性
const count = computed(() => store.state.count)
// 第二种 通过store.getters.getCount  getCount 即为获取器getters里面定义的方法
const count2= store.getters.getCount;
console.log('count2',count2);  //0    


// 定义触发 mutations 的方法  
// 同步方法使用commit来触发 
//需要注意点 方法名是以字符串形式传入进入的
const increment = () => {
  store.commit('increment')
}
const decrement = () => {
  store.commit('decrement')
}

// 定义触发 actions 的方法
// 异步方法使用dispatch来触发
//需要注意点 方法名是以字符串形式传入进入的
const incrementAsync = () => {
  store.dispatch('incrementAsync')
}
</script>

store打印结果图片

vue2+vuex3

store/index.js文件

import Vue from 'vue';
import Vuex from 'vuex';

// 使用 Vuex 插件
Vue.use(Vuex);

// 定义状态
const state = {
    // 计数器
    count: 0,
    // 用户姓名
    userName: 'Guest'
};

// 定义 mutations,用于修改状态
const mutations = {
    // 增加计数器的值
    INCREMENT(state) {
        state.count++;
    },
    // 修改用户姓名
    SET_USER_NAME(state, newName) {
        state.userName = newName;
    }
};

// 定义 actions,用于处理异步操作
const actions = {
    // 异步增加计数器的值
    incrementAsync({ commit }) {
        return new Promise((resolve) => {
            setTimeout(() => {
                commit('INCREMENT');
                resolve();
            }, 1000);
        });
    },
    // 异步修改用户姓名
    setUserNameAsync({ commit }, newName) {
        return new Promise((resolve) => {
            setTimeout(() => {
                commit('SET_USER_NAME', newName);
                resolve();
            }, 1000);
        });
    }
};

// 定义 getters,用于获取状态
const getters = {
    // 获取计数器的值
    getCount(state) {
        return state.count;
    },
    // 获取用户姓名
    getUserName(state) {
        return state.userName;
    }
};

// 创建 store 实例
const store = new Vuex.Store({
    state,
    mutations,
    actions,
    getters
});

export default store;

main.js配置

import Vue from 'vue'
import App from './App.vue'
import store from './store';

new Vue({
  store,
  render: h => h(App),
}).$mount('#app')

 使用

<template>
  <div>
    <!-- 显示计数器和用户名 -->
    <p>当前计数器的值: {{ count }}</p>
    <p>也可以直接通过$store.state.count来访问 state中的数据: 
        {{ $store.state.count  }}</p>
    <p>当前用户名: {{ userName }}</p>
    <p>读取state值的第二种写法: {{ $store.state.userName }}</p>

    <!-- 同步操作按钮 -->
    <button @click="increment">增加计数器</button>
    <button @click="setUserName">修改用户名</button>

    <!-- 异步操作按钮 -->
    <button @click="incrementAsync">异步增加计数器</button>
    <button @click="onSetUserNameAsync">异步修改用户名</button>
  </div>
</template>

<script>
import { mapGetters, mapMutations, mapActions } from 'vuex';

export default {
  computed: {
    // 使用 mapGetters 映射 getters 到计算属性
   ...mapGetters([
      'getCount',
      'getUserName'
    ]),
    // 为了模板使用方便,取别名
    count() {
      return this.getCount;
    },
    userName() {
      return this.getUserName;
    }
  },
  methods: {
    // 使用 mapMutations 映射 mutations 到方法
   ...mapMutations([
      'INCREMENT',
      'SET_USER_NAME'
    ]),
    // 调用同步增加计数器的 mutation
    increment() {
      this.INCREMENT();
    },
    // 调用同步修改用户名的 mutation
    setUserName() {
      this.SET_USER_NAME('NewUser');
    },
    // 使用 mapActions 映射 actions 到方法
   ...mapActions([
      'incrementAsync',
      'setUserNameAsync'
    ]),
    // 调用异步增加计数器的 action
    async onIncrementAsync() {
      await this.incrementAsync();
    },
    // 调用异步修改用户名的 action
    async onSetUserNameAsync() {
      await this.setUserNameAsync('aaaa');
    }
  }
};
</script>

end

本文主要就针对于vuex的基本使用,后续会补充更多关于vuex相关内容。(如有误欢迎指正)

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值