简介
类型VueX,但是对比VueX,pinia对TypeScripts支持更好,把mutation去掉了,同时也是Vue3的响应式的。
现在已经加入了Vue团队,成为正式的一员。
使用
1、创建仓库
// 1、引入
import { defineStore } from "pinia"
// 2、创建仓库
export const useMoneyStore = defineStore("layout", {
// 变量
state:()=>{
return {
price:1 as number // 例子:价格,TypeScripts可以在这里用as指定类型
}
},
// 自动更新的变量,类似于vue 的 computed
getters: {
formatPrice: (state) => { return `¥ ${state.price}`}, // 例子:给价格加个¥符号
},
// 方法
actions:{
resetPrice(){ // 例子:重置价格
this.price = 0
},
addPrice(payload:number){ // 例子:重置价格
this.price += payload
}
}
})
2、使用
vue模板内使用
<template>
<div>
<!-- 3、直接使用state、getter -->
<div>价格:{{store.price}}</div>
<div>价格格式化:{{store.formatPrice}}</div>
</div>
</template>
<script lang='ts'>
export default {
inheritAttrs: false,
name: 'yourName'
}
</script>
<script setup lang='ts'>
// 1、引入
import {useMoneyStore} from "@/store/money/index.ts"
// 2、获得引用实例
const store = useMoneyStore()
// 4、使用actions
const reset = store.resetPrice()
</script>
<style lang='less'>
</style>