定义
Pinia(皮尼亚)是Vue.js官方推荐的下一代状态管理库。
Pinia是一个为 Vue.js 设计的状态管理库。它允许你跨组件或页面共享状态。它的 API 设计非常简洁,与 Vue 3 的 组合 API 完美契合,并且提供了极好的 TypeScript 支持。
pinia既支持Vue2又Vue3的!
基本使用
[1] 安装
javascript
npm i pinia
[2] 创建pinia实例
语法说明
示例
javascript
import { createApp } from 'vue'
import App from './App.vue'
// [1]导入
import { createPinia } from 'pinia'
// [2]创建pinia实例
const pinia = createPinia()
const app = createApp(App)
// [3]将pinia作为插件使用
app.use(pinia)
app.mount('#app')
[3] 定义一个Store
因为pinia是支持Vue2与Vue3的,所以在定义一个Store时,即支持Option Store 风格也支持Setup Store 风格。
语法说明- defineStore API
javascript
import { defineStore } from 'pinia'
defineStore(id, options)
- id: 作为store的唯一标识
- options: 一个选项对象或一个 Setup 函数;此衍生出两种定义 Store 的语法风格:Options Store 和 Setup Store
Setup Store 风格
javascript
import {ref, computed} from 'vue'
import { defineStore } from 'pinia'
// defineStore创建一个模块,user就是模块名
export const userStore = defineStore('user',()=>{
// 使用ref定义的数据相当于state中的数据
const firstName = ref('')
const lastName = ref('')
// computed定义的数据相当于getter
const name = computed(()=> firstName.value+lastName.value)
// 封装的函数相当于actions
function editName(){
firstName.value = 'ren'
lastName.value = 'niuniu'
}
// 移出了mutations这一概念,所有操作都在 actions 中完成
return {firstName, lastName, editName, name}
})
[4-1] 在组件中使用Store
-
引入需要使用的store模块
javascriptimport {useUserStore} from '@/store/user' // 若是需要直接使用state中的数据还需要引入storeToRefs=>直接解构赋值获取的数据不是响应式的 import { storeToRefs } from 'pinia'
-
2\] 使用 ```javascript setup(){ // [1]在setup中调用模块的方法,会返回一个实例对象 const userStore = useUserStore() // [2-1]比如页面需要使用name值,使用storeToRefs解构(响应式) const { name } = storeToRefs(userStore) // [2-2]比如页面需要使用editName方法,直接解构 const { editName } = userStore toEditName(str1,str2){ editName(str1,str2) } // return出去在Dom结构使用 return{ name, toEditName } } ```
javascript
import { defineStore } from "pinia";
// [1] 引入其他模块的store
import { useUserStore } from "./user";
import { computed } from 'vue'
export const useAuthStore = defineStore('auth', ()=>{
// [2] 调用方法获取其他模块store实例化对象
const userInfo = useUserStore()
// 通过实力化对象获取其他模块的state数据
const isAuth= computed(()=> userInfo.name == 'lichaochao')
return { isAuth }
})
优点
