Appearance
Vuex
默认基于 vue3 搭建的,方便pinia对比
介绍
Vuex 是专为 Vue.js 应用程序开发的状态管理模式。它采用集中式存储管理所有组件的状态,并以相应的规则保证状态以一种可预测的方式发生变化。
安装
bash
npm install vuex@next
# 或
yarn add vuex@next基本用法
1. 创建 Store
js
// store/index.js
import { createStore } from 'vuex'
const store = createStore({
state() {
return {
count: 0
}
},
mutations: {
increment(state) {
state.count++
}
},
actions: {
increment({ commit }) {
commit('increment')
}
}
})
export default store2. 挂载 Store
js
import { createApp } from 'vue'
import App from './App.vue'
import store from './store'
const app = createApp(App)
app.use(store)
app.mount('#app')3. 在组件中使用
vue
<template>
<div>
<p>{{ count }}</p>
<button @click="increment">增加</button>
</div>
</template>
<script setup>
import { useStore } from 'vuex'
import { computed } from 'vue'
const store = useStore()
const count = computed(() => store.state.count)
const increment = () => store.commit('increment')
</script>