vue3中pinia的学习使用
听说pinia与vue3更配,便开启了vue3的学习之路(本文只适合vue3)
pinia特点:
1.完整的 typescript 的支持
2.足够轻量,压缩后的体积只有1.6kb
3.去除 mutations,只有 state,getters,actions(这是我最喜欢的一个特点)
4.actions 支持同步和异步
5.没有模块嵌套,只有 store 的概念,store 之间可以自由使用,更好的代码分割
6.无需手动添加 store,store 一旦创建便会自动添加
安装依赖
npm install pinia
main.js引入
import { createPinia } from 'pinia'
app.use(createPinia())
创建store文件夹和index.ts文件
import { defineStore } from 'pinia'
// 定义并导出容器
// 1.容器id唯一,pinia会将容器挂载到根容器
export const userStore = defineStore({
id:'user',
state: () => ({
// 类似组件的data,用来存储全局状态
// 必须是函数:避免在服务端渲染的时候交叉请求导致数据污染
// 必须是箭头函数: ts更好的类型推导
count:0,
name:'张三',
id:''
}),
getters:{
// 类似组件的computed,用来封装计算属性,用缓存功能
// 若使用this,则必须手动指定返回类型,否则类型推导不出
// 函数接受一个可选对象state
// count10 (): number {
// return this.count + 10
// }
count10 (state){
return state.count + 10
}
},
actions: {
// 分装业务逻辑 ,修改state
// 不能使用箭头函数定义action,因为箭头函数绑定外部this
//
logout() {
this.$patch({
name: '',
})
},
// async login(user, password) {
// const userData = await apiLogin(user, password)
// this.$patch({
// name: user,
// ...userData,
// })
// },
},
})
export default userStore
读取使用:
import { defineStore } from 'pinia'
// 定义并导出容器
// 1.容器id唯一,pinia会将容器挂载到根容器
export const userStore = defineStore({
id:'user',
state: () => ({
// 类似组件的data,用来存储全局状态
// 必须是函数:避免在服务端渲染的时候交叉请求导致数据污染
// 必须是箭头函数: ts更好的类型推导
count:0,
name:'张三',
id:''
}),
getters:{
// 类似组件的computed,用来封装计算属性,用缓存功能
// 若使用this,则必须手动指定返回类型,否则类型推导不出
// 函数接受一个可选对象state
// count10 (): number {
// return this.count + 10
// }
count10 (state){
return state.count + 10
}
},
actions: {
// 分装业务逻辑 ,修改state
// 不能使用箭头函数定义action,因为箭头函数绑定外部this
//
logout() {
this.$patch({
name: '',
})
},
// async login(user, password) {
// const userData = await apiLogin(user, password)
// this.$patch({
// name: user,
// ...userData,
// })
// },
},
})
export default userStore
代码地址:https://gitee.com/yuexiayunsheng/dem-list/tree/master/dayDemo2

浙公网安备 33010602011771号