Vue 3 + Pinia 的 demo,包含了如何创建 store、如何在组件中使用 store、如何在组件中更新 store。
- 安装依赖
首先需要安装 Vue 3 和 Pinia 的依赖:
npm i vue@next pinia
- 创建 store
在项目中创建一个 store.ts
文件,用来定义和导出 store,例如:
import { defineStore } from 'pinia'
export const useCounterStore = defineStore({
id: 'counter',
state: () => ({
count: 0
}),
actions: {
increment() {
this.count++
}
}
})
这个 store 定义了一个名为 counter
的 store,其中包含了一个名为 count
的状态和一个名为 increment
的 action。
- 注册 store
在 main.ts
文件中,手动注册 store,例如:
import { createApp } from 'vue'
import App from './App.vue'
import { createPinia } from 'pinia'
import { useCounterStore } from './store'
const app = createApp(App)
// 创建 Pinia 实例
const pinia = createPinia()
// 注册 store
pinia.useStore(useCounterStore)
// 将 Pinia 实例挂载到 Vue 实例上
app.use(pinia)
app.mount('#app')
- 在组件中使用 store
在一个需要使用 store 的组件中,可以使用 useStore
方法来获取 store 实例,例如:
<template>
<div>
<h1>{{ count }}</h1>
<button @click="increment">Increment</button>
</div>
</template>
<script lang="ts">
import { defineComponent } from 'vue'
import { useCounterStore } from './store'
export default defineComponent({
setup() {
const store = useCounterStore()
const count = store.count
const increment = () => {
store.increment()
}
return {
count,
increment
}
}
})
</script>
在上面的组件中,使用 useCounterStore
导入 store,然后使用 useCounterStore()
获取 store 实例,最后获取 store 中的状态和 methods,并在模板中使用。
这样就完成了在 Vue 3 中使用 Pinia 的基本操作。