在Vue 3中使用Pinia,需要按照以下步骤:
- 安装Pinia
你可以通过NPM或Yarn安装Pinia:
npm install pinia
或者
yarn add pinia
- 创建Pinia Store
在Vue 3中,我们可以通过createPinia函数来创建一个全局的Pinia Store。例如:
import { createApp } from 'vue'
import { createPinia } from 'pinia'
import App from './App.vue'
const app = createApp(App)
// 创建Pinia实例
const pinia = createPinia()
app.use(pinia)
app.mount('#app')
这个代码片段中,我们首先使用createApp函数创建Vue应用实例,并导入我们的主组件App.vue。然后,我们通过createPinia函数创建一个全局的Pinia Store实例,并使用Vue应用实例的use方法将其添加到应用中。最后,我们通过mount方法将应用实例挂载到HTML页面上。
- 创建模块
在Pinia中,模块是一组相关的状态和操作,通常与一个特定的功能相关。我们可以使用defineStore函数来创建一个模块。例如:
import { defineStore } from 'pinia'
export const useCounterStore = defineStore({
id: 'counter',
state: () => ({
count: 0
}),
actions: {
increment() {
this.count++
},
decrement() {
this.count--
}
}
})
这个代码片段中,我们使用defineStore函数创建一个名为useCounterStore的模块。在state属性中,我们定义了一个名为count的状态。在actions属性中,我们定义了两个操作increment和decrement,它们可以通过this关键字访问count状态。
- 使用模块
我们可以在Vue组件中使用useStore函数来获取一个Pinia Store实例,并在模板中使用它的状态和操作。例如:
<template>
<div>
<p>{{ counter.count }}</p>
<button @click="counter.increment()">Increment</button>
<button @click="counter.decrement()">Decrement</button>
</div>
</template>
<script>
import { defineComponent } from 'vue'
import { useCounterStore } from './store'
export default defineComponent({
setup() {
// 获取Counter Store实例
const counter = useCounterStore()
return {
counter
}
}
})
</script>
在这个代码片段中,我们首先导入useCounterStore模块,并在setup函数中获取了它的实例。在模板中,我们可以通过counter对象访问count状态,以及increment和decrement操作。