安装
npm i pinia
pnpm i pinia
main.ts中引入
import { createPinia } from 'pinia'//引入createPinia用于创建pinia
app.use(createPinia())//使用pinia
组合式写法——Setup Store 更推荐
setup store更加灵活
ref() 就是 state 属性
computed() 就是 getters
function() 就是 actions
counter.ts —— pinia文件
import { ref, computed } from 'vue'
import { defineStore } from 'pinia' // 导入ref、computed和defineStore三个函数
// 导出一个名为useCounterStore的常量,该常量是一个defineStore函数的返回值
export const useCounterStore = defineStore('counter', () => {
// 定义一个名为count的ref变量,初始值为0
const count = ref(0)
// 定义一个名为doubleCount的computed变量,其值为count.value * 2
const doubleCount = computed(() => `点击双倍${count.value * 2}`)
// 定义一个名为increment的函数,每次调用时将count.value加1
const add = () => {if(count.value < 10) count.value++}
// 返回count、doubleCount和increment三个变量
return { count, doubleCount, add }
})
获取store 使用
//页面
<div @click="showNum">{{ doubleCount }}</div>
//js
import {storeToRefs} from 'pinia' //引入store ref化 解构响应式
import {useCounterStore} from '@/stores/counter.ts' //引入编写的pinia store文件
const counterStore = useCounterStore();
let {doubleCount,count}= storeToRefs(counterStore);//只有getter和state能使用storeToRefs
let {add} = counterStore;//action是函数 不需要用storeToRefs解构 也不能用
const showNum = ()=>{
add()
}
注意,要让 pinia 正确识别 state,你必须在 setup store 中返回 state 的所有属性。这意味着,你不能在 store 中使用私有属性。不完整返回会影响 SSR ,开发工具和其他插件的正常运行。
选项式写法——Option Store
import { defineStore } from "pinia";
// 导出一个名为 useUserStore 的 Pinia store,用于管理用户状态
export const useUserStore = defineStore("user", {
// 定义 store 的状态
state: () => ({ //定义一个store,用于管理用户状态
// 初始化用户状态为 null
user: 'zhangsan' as string | null,
}),
// 定义改变状态的方法
actions: {
// 设置用户状态
setUser(user: any) {
this.user = user;
},
// 清除用户状态
clearUser() {
this.user = null;
},
},
// 定义基于状态的计算属性
getters: {
// 获取用户状态,当前为空,需要实现具体逻辑
getUser: (state) => {
return state.user;
}
}
})
获取
<div @click="setUser('王五')">
{{ user }}
</div>
import { storeToRefs } from 'pinia'
import { useUserStore } from '@/stores/user.ts'
let userStore = useUserStore()
let { user } = storeToRefs(userStore)
let {setUser} = userStore
VScode插件
Pinia Snippets
pinia官网
https://pinia.vuejs.org/zh/introduction.html