vue3插件-pinia

文章目录

  • 一、pinia是什么?
  • 二、使用步骤
    • 1.安装并注入
    • 2.核心概念与基本使用
  • 代码参考

一、pinia是什么?

Pinia 是一个用于 Vue 的状态管理库,类似 Vuex, 是 Vue 的另一种状态管理方案
Pinia 支持 Vue2 和 Vue3

二、使用步骤

1.安装并注入

安装

# 使用 npm
npm install pinia@next
# 使用 yarn
yarn add pinia@next

注入vue

import { createPinia } from 'pinia';
app.use(createPinia());

2.核心概念与基本使用

Store 是一个保存状态和业务逻辑的实体,可以自由读取和写入,并通过导入后在 setup 中使用
创建一个 store.ts和demo.ts

// store.ts
import { defineStore } from "pinia";
import { useDemoStore } from "./demo";

// defineStore 调用后返回一个函数,调用该函数获得 Store 实体
export const useStore = defineStore({
  // id: 必须的,在所有 Store 中唯一
  id: "myGlobalState",
  // state: 返回对象的函数
  state: ()=> ({
    count: 1
  }),
  getters: {
    getCount(state) {
      return state.count + 1;
    },
    getDemo() {
      const demoStore = useDemoStore();
      return demoStore.count;
    },
  },
  actions: {
    setCount(count: number) {
      this.count = count;
    },
  },
});

// demo.ts
import { defineStore } from "pinia";

export const useDemoStore = defineStore({
  id: "otherState",
  state: ()=> ({
    count: 5
  }),
});

使用

//demo.vue
import { storeToRefs } from "pinia";

import {useStore} from '@/store'

const store = useStore()

// 解构会丧失响应式,需使用storeToRefs
const {count} = storeToRefs(store)

store.setCount(10000)

代码参考

https://github.com/wangliuyong/vue3-vite

你可能感兴趣的:(javascript,vue.js,typescript)