什么是pinia
pinia其实就是Vuex5,这是尤雨溪老师在直播中提到的,所以它俩是一致的东西,只是vuex第五个版本之后就叫pinia了。Pinia官方文档传送门
官方文档首页是很可爱的小菠萝
pinia是同时支持vue2和vue3的,vuex4只支持vue3的 Composition API,所以这点来看pinia的支持性是非常好的
核心语法
pinia的核心语法有State,Getters,Actions,Plugins以及Stores outside of components(在组件外进行调用)。可以发现跟vuex4相比,pinia少了一个Mutation,在pinia中,是直接使用actions去做状态的修改。在actions中以前我们是通过state.去获得状态,而在这里可以直接通过this. 获取状态
起步
安装pinia
yarn add pinia
或者使用 npm
npm install pinia
AI 代码解读
可以在src下新建一个store文件夹 用来存放pinia相关的东西
index.ts
import { defineStore } from 'pinia'
export const useCounterStore = defineStore('counter', {
state: () => {
return { count: 0 }
},
// could also be defined as
// state: () => ({ count: 0 })
actions: {
increment() {
this.count++
},
},
})
AI 代码解读
访问state
我们可以直接通过state.访问
const store = useStore()
store.counter++
AI 代码解读
使用Getters
要注意,在pinia中,Getters和state里面不能使用相同的名字
export const useStore = defineStore('main', {
state: () => ({
counter: 0,
}),
getters: {
doubleCount: (state) => state.counter * 2,
},
})
AI 代码解读
Actions
定义和处理业务逻辑
export const useStore = defineStore('main', {
state: () => ({
counter: 0,
}),
actions: {
increment() {
this.counter++
},
randomizeCounter() {
this.counter = Math.round(100 * Math.random())
},
},
})
AI 代码解读
Pinia实战-登录状态的管理
新建store文件,在下面index.ts中编辑pinia的使用:
- 在state中定义了isAuthenticated表示登录状态,对象user中存放登录的用户信息,初始状态为空
- 在actions中进行定义,setAuth方法判断isAuth的值控制用户的登录状态,setUser方法将用户的信息写入user中
import { defineStore } from 'pinia'
import {userType} from '../utils/types'
export const useAuthStore = defineStore('auth', {
state: () => {
return { isAuthenticated:false,user: {} }
},
getters: {
getAuthenticated: (state) => state.isAuthenticated,
getUser: (state) => state.user,
},
actions: {
setAuth(isAuth:boolean){
if(isAuth){
this.isAuthenticated = isAuth;
}else {
this.isAuthenticated = false;
}
},
setUser(user: userType | null){
if(user){
this.user = user;
}else {
this.user = {}
}
}
},
})
AI 代码解读
定义好了pinia,然后去登录界面使用
login.vue: 这里我就只展示使用pinia的部分了
首先要引入我们在pinia中定义的东西
import { useAuthStore } from "../store";
const store = useAuthStore();
AI 代码解读
解析token之后,信息保存在decode之中,然后直接通过store的setAuth和setUser方法传入对应的参数
// 解析token
const decode: userType = jwt_decode(token);
store.setAuth(!!decode);
store.setUser(decode);
AI 代码解读
效果实现
在没有登录的时候,也就是还没有token,我们查看控制台vue:
可以看到下图登录状态为false,用户信息user中也为空
然后我们点击登录,此时token已经保存,然后查看控制台
可以看到,用户的信息以及登录状态都获取到了
用户登录之后,我们将用户的信息保存到pinia中,这样在管理系统中可以很方便的调用用户信息进行其他的操作~