多多读书
314 字
2 分钟
一分钟上手 Pinia

Pinia 是一个状态管理库,用来代替 Vuex。尽管有很多文档和教程介绍如何使用 Pinia,但大多数都是基于 Vue2 的写法。如果你使用的是 Vue3,那么可以不必阅读这些教程。下面我将介绍如何使用 Vue3 的最简单写法。

安装#

yarn add pinia
# 或者使用 npm
npm install pinia

创建一个 Pinia 实例(根 store)并将其传递给应用:

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

const pinia = createPinia() // 实例化
const app = createApp(App)

app.use(pinia) // 注入
app.mount('#app')

创建 Store#

创建一个文件或文件夹来存放 Store 的定义,Vue3 中可以直接使用setup()函数的语法,例如:

import { ref } from 'vue'

export const useCounterStore = defineStore('counter', () => {
  // 这部分与setup语法完全相同
  const count = ref(0)
  function increment() {
    count.value++
  }

  return { count, increment }
})

组件调用#

然后在组件内引用时,需要将其写在组件的setup函数中,例如:

<script setup>
  import {useCounterStore} from './path/to/store' const counterStore = useCounterStore() /** * 调用 * counterStore.count
  * counterStore.increment */
</script>

很简单吧?你可以将 Store 想像成全局存储的setup函数调用。当然你想要有更深入的了解,可能直接查看文档https://pinia.vuejs.org/zh/getting-started.html

一分钟上手 Pinia
https://fuwari.vercel.app/posts/20230920/
作者
我也困了
发布于
2023-09-20
许可协议
CC BY-NC-SA 4.0