Pinia--Vue存储库,在Vue3+ts中全局定义以及简单使用

Pinia 中文文档

安装:

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

在项目的 main.js 文件中引入:

import { createPinia,Pinia } from "pinia";

const pinia = createPinia();

app.use(pinia);

然后你在项目中定义一个 文件夹: counter==>test.ts

import { defineStore } from "pinia";

export const useCounterStore = defineStore('counter', { // counter为这个存储库的名字
    state: () => {
      return { count: 0 }
    },
    // 也可以定义为
    // state: () => ({ count: 0 })
    actions: {
      increment() {
        this.count++
      },
    },
  })

在组件中使用:

import { useCounterStore } from '@/stores/counter'

export default {
  setup() {
    const counter = useCounterStore(); //这里的counter就是我们在test.ts中的存储库的counter名字

    console.log(counter.count) // 打印: 0

    counter.count++
    // 带自动补全 ✨
    counter.$patch({ count: counter.count + 1 })
    // 或使用 action 代替
    counter.increment()
  },
}

猜你喜欢

转载自blog.csdn.net/m0_58293192/article/details/130233761