vue状态管理
Vuex
基本使用
store/index.js
import { createStore } from "vuex"; const store = createStore({ state: () => ({ counter:0 }) }) export default store
App.vue
<stript> import {useStore} from 'vuex' console.log(useStore.state.counter) // 0 </stript>
属性
state
actions
异步操作
提交mutation
$store.dispatch('actionFn',)
incrementAction(context,payload){} :
modules
modules/home.js
modules/about.js
export default { namespaced: true // 命名空间 state(){ return { } }, actions:{ }, getters:{ counter(){ } }, mutations:{ } } // store/index.js import homeModel from modules/home.js ... modules:{ home: homeModel } ...
命名空间
- 默认情况下,getters mutations actions 都是注册到全局store中
- namespaced: 开启命名空间
- 取值时
$store.getters['home/counter']
修改或派发根组件
commit('mutationsFn',payload,{root:true})
dispatch('actionsFn',payload,{root:true})
getters
(state,getters): getters拿到所有的getter
mutations
修改state,必须提交mutation,才符合规范
$store.commit('mutationFn',payload)
映射
import {mapState} from 'vuex'
// option API
...mapState(['name','level'])
...mapState({
sName:state=>stat.name,
})
// compositionAPI
const store = useStore()
const {name,level} = toRefs(store.state)
const mes = computed(()=>store.getters.mes)
Pinia
与Vuex的对比
- mutations不存在了
- mutation常常被认为是非常冗长的
- mutation是为了devtool 集成设计的
- 更好的TS语法支持
- 不再有module的嵌套结构
- 扁平化,灵活使用每一个store
使用
// stores/index.js
import {createPinia} from 'pinia'
const pinia = createPinia()
export default pinia
// main.js
import pinia from '@/stores'
app.use(pinia)
// stores/counter.js
import {defineStore} from 'pinia'
export default const useCounter = defineStore('counter',{
state(){
return {
counter:0
}
}
})
// Home.vue
import useCounter from '@/stores/counter.js'
const store = useCounter()
console.log(store.counter)
核心
一旦store实例被创建,就可以访问state,getters,actions中的变量
state
等同组件的data
默认是可以读写的
操作
// 重置
useStore.$reset()
// 修改多个值
useStore.$patch({
name:'xxx',
age;19
})
// 替换state对象(合并)
useStore.$state = {
}
getters
等同组件的computed
getters:{
// 基本使用
dbCounter(state){
return state.counter*2
}
// this指向store实例
dbCounter2(){
return this.counter*2
}
// getters中用到了其他getters的数据
showMes(state){
const userStore = useUser()
return userStore.name+':'+state.age
}
// 返回一个函数
showMes2(){
return funciton(){
...
}
}
}
actions
等同组件的methods
actions:{
incrementCounter(payload){
console.log(payload)
},
async decrementCounter(){
const a = await fetch
}
}
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 【自荐】一款简洁、开源的在线白板工具 Drawnix
· 没有Manus邀请码?试试免邀请码的MGX或者开源的OpenManus吧
· 无需6万激活码!GitHub神秘组织3小时极速复刻Manus,手把手教你使用OpenManus搭建本
· C#/.NET/.NET Core优秀项目和框架2025年2月简报
· DeepSeek在M芯片Mac上本地化部署