Pinia的介绍
是什么
Pinia 是 Pinia 的官方状态管理库,用来管理 全局共享状态(state)。
它主要用于 Vue.js 应用中,取代早期常用的 Vuex。
简单理解:Pinia = Vue 的全局数据仓库(store)
当多个组件需要共享数据时,不需要层层 props 传递,可以直接从 Pinia 读取或修改。
Pinia 解决什么问题
假设一个 Vue 项目:
App
├─ Header (显示用户名)
├─ Sidebar (显示权限)
└─ Profile (修改用户信息)
如果不用 Pinia:
- 数据要一层层
props - 修改要
$emit - 组件关系复杂
使用 Pinia:
Pinia Store
│
┌────────┼────────┐
Header Sidebar Profile
所有组件直接访问同一个 store。
Pinia 的使用(uni-app)
安装 Pinia
npm install pinia
uni-app 内置了 Pinia,不需要安装
在 main.js 注册 Pinia
import App from './App'
import { createSSRApp } from 'vue';
import * as Pinia from 'pinia';
export function createApp() {
const app = createSSRApp(App);
app.use(Pinia.createPinia());
return {
app,
Pinia, // 此处必须将 Pinia 返回
};
}
作用:让整个 uni-app 项目都可以使用 Pinia
创建 store
通常会创建一个 stores 文件夹。
stores
└─ user.js
创建的模版:
defineStore('store名字', () => {
// 1 声明变量
const xxx = ref()
// 2 声明函数
function fn() {}
// 2 箭头函数写法
const fn = () => {}
// 3 返回
return {
xxx,
fn
}
})
比如:
import { defineStore } from "pinia"
import { ref } from "vue"
export const useUserStore = defineStore("user", () => {
// 创建变量
const name = ref("Tom")
const age = ref(20)
//创建函数
const changeName = (newName) => {
name.value = newName
}
// return 暴露出去
return {
name,
age,
changeName
}
})
页面中使用 store
<script setup>
import { useUserStore } from "@/stores/user"
const userStore = useUserStore()
const change = () => {
userStore.changeName("Jack")
}
</script>
<template>
<view>
<view>
用户名:{{ userStore.name }}
</view>
<button @click="change">
修改用户名
</button>
</view>
</template>