Pinia
pinia中不再有主仓库之说,store文件夹下每一个文件就是一个子模块仓库,其中直接通过defineStore()去定义仓库即可
文件夹如下:
|---store
|---roles.ts//角色仓库
|---users.ts//用户仓库
一、全局挂载pinia
import { createPinia } from "pinia"
const pinia =createPinia()
。。。
app.use(pinia)
。。。
二、定义store仓库
通过defineStore(“仓库名称”,{ 其他配置(即三大核心) })
import { defineStore } from "pinia" #引入defineStore
#配置仓库
const useRolesStore = defineStore("roles",{
state:()=>({}),//存储公共数据
getters:{ },//计算属性
actions:{ }//同步异步方法
})
#暴露仓库
export default useRolesStore
三、仓库中state/actions的使用
-
state:用于保存公共数据,它是一个属性,属性值为函数,函数的返回值就是公共数据
-
getters:计算属性,每个计算属性接收一个参数state,必须有一个返回值
-
actions:用于保存同步和异步方法,在其中使用state中的数据时,直接通过this.数据,即可访问和修改state中的数据
import { defineStore } from "pinia" const useRolesStore = defineStore("roles", { state: ()=>({ num: 2, roleData: []//初始数据 }), getters: { doubleNum: (state)=>state.num*2 }, actions: { //异步方法 async getRolesAsync(){ const res=await getRolesApi()//发送异步请求并获取数据 if (res.code) { this.rolesData =res.data//直接通过this.roleData访问仓库中的数据并赋值:this指代仓库对象 } } } }) export default useRolesStore
四、组件使用仓库数据与方法
1、调用仓库方法actions
引入文件–调用并生成仓库对象–使用仓库中的方法
//在组件中
import useRolesStore from "仓库文件路径"#引入
const roleStore=useRolesStore()#生成仓库对象
const getRolesFn=async ()=>{
roleStore.getRolesAsync()#调用仓库中的方法
}
2、使用仓库数据state
(1)、通过仓库对象.数据名称直接使用
//在组件中
import useRolesStore from "仓库文件路径"#引入
const roleStore=useRolesStore()#生成仓库对象
在html中直接#rolesStore.rolesData
(2).通过计算属性接收
const rolesData=computed ( ()=>{
return rolesStore.rolesData
} )
3、使用仓库计算属性getters
使用方法同state
五、pinia和vuex的区别
(1)pinia它没有mutation,他只有state,getters,action【同步、异步】使用他来修改state数据
(2)pinia他默认也是存入内存中,如果需要使用本地存储,在配置上比vuex麻烦一点
(3)pinia语法上比vuex更容易理解和使用,灵活。
(4)pinia没有modules配置,每一个独立的仓库都是definStore生成出来的
(5)pinia的state是一个对象返回一个对象,和组件的data是一样的语法
注:pinia适用于中小型项目;vuex适用于大型项目
Pinia中每个store文件是一个子模块,通过defineStore定义。全局挂载后,可按需导入和使用。state保存数据,getters提供计算属性,actions处理同步和异步操作。与Vuex不同,Pinia没有mutation,更简洁灵活,适合中小型项目。
1950

被折叠的 条评论
为什么被折叠?



