目录
认识pinia
pinia是一个全局状态管理工具
Pinia.js具有以下特点
- 完整的 ts 的支持;
- 足够轻量,压缩后的体积只有1kb左右;
- 去除 mutations,只有 state,getters,actions;
- actions 支持同步和异步;
- 代码扁平化没有模块嵌套,只有 store 的概念,store 之间可以自由使用,每一个store都是独立的
- 无需手动添加 store,store 一旦创建便会自动添加;
- 支持Vue3 和 Vue2
1. 起步 安装
yarn add pinia
npm install pinia
2. 引入注册
import { createApp } from 'vue'
import App from './App.vue'
import ElementPlus from 'element-plus'
import 'element-plus/dist/index.css'
import {createPinia} from "pinia";
const pinia = createPinia()
const app = createApp(App)
app.use(ElementPlus)
app.use(pinia)
app.mount('#app')
3. 初始化仓库store
需要以下几步
1.新建一个文件夹Store
2.新建文件[name].ts
3.定义仓库Store
import { defineStore } from 'pinia'
4.存储是使用定义的defineStore()
,并且它需要一个唯一的名称,作为第一个参数传递
我们定义了一个枚举去做这个唯一值
5.定义值
State 箭头函数 返回一个对象 在对象里面定义值
getters 类似于computed
actions 可以提交一些同步或异步的方法来改变state
import {defineStore} from "pinia";
import {Namespace} from "./namespace.ts";
export const useStore = defineStore(Namespace.TEST, {
state: () => {
return {
count: 0
}
},
getters: {
},
actions: {
}
});
使用pinia---state
在vue中需要调用导出的pinia 调用这个useStore函数,拿到他的返回值对象即可进行使用
<script setup lang='ts'>
import {useStore} from "./store";
const Test = useStore()
console.log(Test.count)
</script>
<template>
</template>
<style scoped>
</style>
修改state值的方式
1. 直接修改
<script setup lang='ts'>
import {useStore} from "./store";
const Test = useStore()
</script>
<template>
<button @click="Test.count++">增加</button>
{
{Test.count}}----{
{Test.name}}
</template>
<style scoped>
</style>
2. 批量修改state的值
在他的实例上有$patch方法可以批量修改多个值
$patch传入一个对象,进行修改
<script setup lan