1. 安装 Pinia
npm install pinia
2. 创建 Pinia 实例并引入到项目
import { createApp } from 'vue'
import { createPinia } from 'pinia'
import App from './App.vue'
// 创建 Pinia 实例
const pinia = createPinia()
// 创建 Vue 应用并使用 Pinia
const app = createApp(App)
app.use(pinia)
app.mount('#app')
3 定义 Store
在 stores 目录下创建一个 store 文件(例如 counter.js):
import { defineStore } from 'pinia'
// 定义并导出一个 Store,参数1:唯一ID,参数2:配置对象
export const useCounterStore = defineStore('counter', {
// 状态(类似 Vuex 的 state)
state: () => ({
count: 0,
user: {
name: '张三',
age: 20
}
}),
// 计算属性(类似 Vuex 的 getters)
getters: {
// 计算双倍数值
doubleCount: (state) => state.count * 2,
// 使用 this 访问其他 getter
doubleCountPlusOne() {
return this.doubleCount + 1
}
},
// 方法(类似 Vuex 的 actions,可异步)
actions: {
increment() {
// 直接修改状态
this.count++
},
// 异步操作(例如接口请求)
async fetchUser() {
// 模拟接口请求
const res = await new Promise(resolve => {
setTimeout(() => {
resolve({ name: '李四', age: 25 })
}, 1000)
})
this.user = res
}
}
})
4. 在组件中使用 Store
<template>
<div>
<p>计数: {{ counterStore.count }}</p>
<p>双倍计数: {{ counterStore.doubleCount }}</p>
<p>用户名: {{ counterStore.user.name }}</p>
<button @click="counterStore.increment">加1</button>
<button @click="counterStore.fetchUser">获取用户信息</button>
<button @click="resetCount">重置计数</button>
</div>
</template>
<script setup>
import { useCounterStore } from '@/stores/counter'
// 获取 Store 实例
const counterStore = useCounterStore()
// 重置计数的方法
const resetCount = () => {
// 方法1:直接修改
counterStore.count = 0
// 方法2:使用 $reset() 重置为初始状态
// counterStore.$reset()
// 方法3:使用 $patch 批量修改
// counterStore.$patch({
// count: 0,
// user: { ...counterStore.user, age: 20 }
// })
}
</script>