你可以通过 npm 或 yarn 来安装 Pinia。
- npm install pinia
- # 或者
- yarn add pinia
在 Vue 应用的入口文件(如 main.js
或 main.ts
)中,你需要导入 createPinia
并与 Vue 应用实例进行绑定。
- import { createApp } from 'vue'
- import { createPinia } from 'pinia'
- import App from './App.vue'
-
- const app = createApp(App)
- const pinia = createPinia()
- app.use(pinia)
- app.mount('#app')
使用 Pinia,你可以通过 defineStore
函数来创建 store。每个 store 都是一个独立的实体,包含其自己的状态、getters 和 actions。
- import { defineStore } from 'pinia'
-
- export const useCounterStore = defineStore('counter', {
- state: () => {
- return { count: 0 }
- },
- getters: {
- doubleCount: (state) => state.count * 2,
- },
- actions: {
- increment() {
- this.count++
- },
- decrement() {
- this.count--
- },
- },
- })
在 Vue 组件中,你可以通过导入并使用刚才定义的 store 来访问其状态、getters 和 actions。
- <template>
- <div>
- <p>Count: {{ count }}</p>
- <p>Double Count: {{ doubleCount }}</p>
- <button @click="increment">Increment</button>
- <button @click="decrement">Decrement</button>
- </div>
- </template>
-
- <script>
- import { useCounterStore } from './stores/counter'
-
- export default {
- setup() {
- const counterStore = useCounterStore()
-
- return {
- count: counterStore.count,
- doubleCount: counterStore.doubleCount,
- increment: counterStore.increment,
- decrement: counterStore.decrement,
- }
- },
- }
- </script>