一、Pinia 介绍
全局状态管理工具
Pinia.js 有如下特点:
- 完整的 ts 的支持;
- 足够轻量,压缩后的体积只有1kb左右;
- 去除 mutations,只有 state,getters,actions;
- actions 支持同步和异步;
- 代码扁平化没有模块嵌套,只有 store 的概念,store 之间可以自由使用,每一个store都是独立的
- 无需手动添加 store,store 一旦创建便会自动添加;
- 支持Vue3 和 Vue2
官方文档Pinia
git 地址 https://github.com/vuejs/pinia
1. 安装
npm install pinia
2. 引入并注册 Vue3
import {
createApp } from 'vue'
import App from './App.vue'
import {
createPinia} from 'pinia'
const store = createPinia()
let app = createApp(App)
app.use(store)
app.mount('#app')
3. vue2 使用
import {
createPinia, PiniaVuePlugin } from 'pinia'
Vue.use(PiniaVuePlugin)
const pinia = createPinia()
new Vue({
el: '#app',
// other options...
// ...
// note the same `pinia` instance can be used across multiple Vue apps on
// the same page
pinia,
})
二、初始化仓库Store
1.新建一个文件夹store (src下)
2.新建文件[name].ts (index.ts)
3.定义仓库Store
import {
defineStore } from 'pinia'
4.我们需要知道存储是使用定义的defineStore(),并且它需要一个唯一的名称,作为第一个参数传递
可以把名称抽离出去了(新建文件store-name.ts)
export const enum Names {
//enum 枚举
Test = 'TEST'
}
index.ts 中 store 引入
import {
defineStore } from 'pinia'
import {
Names } from './store-name'
export const useTestStore = defineStore(Names.Test, {
}) // 这里 定义名称 前面的开头 要用 use
这个名称,也称为id,是必要的,Pania 使用它来将商店连接到 devtools。将返回的函数命名为use…是可组合项之间的约定,以使其使用习惯。
- 定义值
State 箭头函数 返回一个对象 在对象里面定义值
import {
defineStore } from 'pinia'
import {
Names } from './store-namespce'
export const useTestStore = defineStore(Names.Test, {
state:()=>{
// 这里
return {
current:1
}
},
//类似于computed 可以帮我们去修饰我们的值 (有缓存)
getters: {
},
// 类似 methods 可以做同步 异步 去提交 state
actions: {
}
})
- 使用
import {
useTestStore} from "./store/index" // 引入
const Test = useTestStore()
<div>
{
{
Test.current}} ---- {
{
Test.name}}
</div>
三、Store修改值
1. State 是允许直接修改值的 例如current++
<template>
<div>
<button @click="Add">+</button>
<div>
{
{
Test.current}}
</div>
</div>
</template>
<script setup lang='ts'>
import {
useTestStore} from './store'
const Test = useTestStore()
const Add = () => {
Test.current++ // 这里 可以直接修改
}
</script>
<style>
</style>
2. 批量修改State的值 ($path方法)
在他的实例上有$patch方法可以批量修改多个值
<template>
<div>
<button @click="Add">+</button>
<div>
{
{
Test.current}}
</div>
<div>
{
{
Test.age}}
</div>
<<