pinia

本页目录

Pinia 用来在多个 Vue 组件之间共享状态。

安装并注册

npm install pinia
bash

在 src/main.js 中注册 Pinia:

import { createApp } from 'vue'
import { createPinia } from 'pinia'
import App from './App.vue'

createApp(App).use(createPinia()).mount('#app')
js

定义 store

在 src/stores/counter.js 中定义共享状态和修改方法:

import { defineStore } from 'pinia'
import { ref } from 'vue'

export const useCounterStore = defineStore('counter', () => {
  const count = ref(0)

  function increment() {
    count.value++
  }

  return { count, increment }
})
js

在组件中使用

以下组件放在 src/App.vue。直接用 counter.count 读取状态,用 counter.increment() 修改状态。

<script setup>
import { useCounterStore } from './stores/counter'

const counter = useCounterStore()
</script>

<template>
  <button @click="counter.increment()">{{ counter.count }}</button>
</template>
vue

需要解构状态时,用 storeToRefs(counter) 保留响应性。