vue3使用vuex

本文详细介绍了如何在Next.js应用中使用Vuex进行用户信息管理,包括store的创建、state和getter的定义、mutations处理同步操作、actions处理异步操作以及模块化的优点。同时讨论了在<scriptsetup>中使用mapState、mapGetters、mapMutations和mapActions的方法。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

使用场景:保存用户信息

安装

npm install vuex@next --save || yarn add vuex@next --save

在store文件夹,默认有index.js文件
import { createStore } from 'vuex'
import { ModuleUser } from './user.js'
// 类似 Redux 中的建立状态树

export default store({
  
  // 1、 存储所有全局数据
  state: {
    
  },
 
  // 2、 需要通过计算获取state里的内容获取的数据
  // 只能读取不可修改
  getters: {
   
  },
 
  //  3、定义对state的各种操作
  // why不直接实现在mutation里需要写到action里?
  // mtations不能执行异步操作。aq:从云端获取信息-->(等待云端反馈)更新到state异步操作
  // 因此说:对于异步操作需要放到action里,简单的直接赋值操作可以直接放到mutation里
  mutations: {
    updataUser(state,user){
      state.user.username = user.username;
    }
  },

  // 3、定义对state的各种操作
  // actions无法直接修改state,需要在mutations里更新
  // mutation不支持异步,所以需要在action里写api到url
   
  actions: {
      // 比说action定义了更新state的操作
      // 但是不可对其直接修改
      // 所有的修改操作必须放到mutations里
      //模仿登录验证时向服务器发送请求,并接受获取数据
      //根据发送的username和password得到access里的userid,获取用户信息
  },

  // state中信息过长时
  // 用来将state进行分割
  // 如下,将state树分割出一个user state。
  modules: {
  	user: ModuleUser,
  }
})

user.js
// user. js
const ModuleUser = {
 state: {
     id: "",
     username: "",
     photo: "",
 },

 getters: {
 },

 mutations: { 
   updateUser(state,user){
     state.id = user.id;
     state.username = user.username;
   }, 
 },

 actions: {
   logout({commit}){
			commit("updateUser",{
        id:null,
        username:''
      })
		}
 }

 modules: {
 }
};

export default ModuleUser;
main.js
import store from './store'
app.use(store) //注册vuex
vue页面使用
<script setup>
import { useStore } from 'vuex'
const store = useStore()
console.lgo(store.state.user.id)

//触发 userModule Mutations 修改State中的状态 
store.commit('ModuleUser/updateUser',{
  id:21,
  username:'name'
}) 

//触发Action
store.dispatch('logout') 


store.dispatch('initApp')
.then((res) => {})
.catch(err=>{})


</script>
Mutations 的特点
  • Mutations 是同步修改 state 状态的。
  • Mutations 修改 state 必须是通过 store.commit() 来触发。
  • Mutations 只能处理同步操作。
Action 的特点和作用
  • Action 是异步的,用于处理异步操作或复杂的操作逻辑。
  • Action 一般不直接修改 state 状态,而是提交 Mutations 完成具体的状态变更。
  • Action 可以提交 Mutations,也可以赋值 state 状态。
  • Action 通过 store.dispatch 触发。
Getter 的特点和作用
  • Getter 访问时不需要调用,是在模块中对 state 进行一个辅助性的处理。
  • Getter 不会对 state 数据进行修改,只是对 state 数据进行加工处理。
  • Getter 的作用是从 store 中派生状态,即从 store 中获取状态。
  • 组件中很少直接使用 state,因为 state 的结构可能会改变,这会导致需要修改组件中的所有使用到这些 state 的地方。而使用 Getter,可以维护一种稳定的接口。
Module 的特点和作用
  • 命名空间: Module 可以减少把 State、Mutation、Action、Getter 加入到全局命名空间中的问题,避免团队开发时命名冲突的问题。
  • 优化组织结构:当一个 Store 变得非常大时,使用Module将它们拆分成较小而简单的部分可以更轻松地理解和维护。
  • 代码重复使用:可以为多个模块中共享代码提供便利。

辅助函数

使用组合式API时,如在<script setup>语法糖中,我们无法使用辅助函数,因为这些辅助函数的底层是调用的this.$store,而在组合式API中,不存在this,所以辅助函数在组合式API中无法使用

mapState

mapState用于将state映射到Vue组件的计算属性中。

// 在组件中使用 mapState
import { mapState } from 'vuex'

export default {
  computed: {
    ...mapState({
      id: state => state.user.id,
      name: state => state.user.name
    })
  }
}
mapGetters

mapGetters用于将getter映射到Vue组件的计算属性中。

// 在组件中使用 mapGetters
import { mapGetters } from 'vuex'

export default {
  computed: {
    ...mapGetters({
      doneTodos: 'doneTodos',
      doneTodosCount: 'doneTodosCount'
    })
  }
}
mapMutations

mapMutations用于将mutation映射到Vue组件的methods中。

// 在组件中使用 mapMutations
import { mapMutations } from 'vuex'

export default {
  methods: {
    ...mapMutations([
      'updateUser', // 将 `this.increment()` 映射为 `this.$store.commit('increment')`
    ])
  }
}
mapActions

mapActions用于将action映射到Vue组件的methods中。

// 在组件中使用 mapActions
import { mapActions } from 'vuex'

export default {
  methods: {
    ...mapActions([
      'incrementAsync', // 将 `this.incrementAsync()` 映射为 `this.$store.dispatch('incrementAsync')`
      'addAsync' // 将 `this.addAsync()` 映射为 `this.$store.dispatch('addAsync')`
    ])
  }
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值