1.什么事pinia
Pinia 是 Vue 的专属状态管理库,它允许你跨组件或页面共享状态。
2.main.js文件中配置
3.stores中配置
首先导入
import { defineStore } from 'pinia'
其次导出一个仓库
export const useUserStore =defineStore('user',()=>{
const userInfo = ref({name:'mumu',score:200})
const token = ref('')
}
return {userInfo,token,login}
})
4.组件中使用
首先要导入定义的仓库
5.定义 Store
在深入研究核心概念之前,我们得知道 Store 是用 defineStore() 定义的,它的第一个参数要求是一个独一无二的名字:
import { defineStore } from 'pinia'
// 你可以对 `defineStore()` 的返回值进行任意命名,但最好使用 store 的名字,同时以 `use` 开头且以 `Store` 结尾。(比如 `useUserStore`,`useCartStore`,`useProductStore`)
// 第一个参数是你的应用中 Store 的唯一 ID。
export const useStore = defineStore('main', {
// 其他配置...
})
可以认为 state 是 store 的数据 (data),getters 是 store 的计算属性 (computed),而 actions 则是方法 (methods)。