Vue3 Pinia使用
发布时间
阅读量:
阅读量
Vue3 Pinia使用
在学习 Vue2 中一定都知道,在 vue2 版本中,如果想要使用状态管理器,那么一定是集成 Vuex,首先说明一点,Vuex 在 vue3 项目中依旧是可以正常使用的,是 vue 项目的正规军。但是,今天我们学习一下Pinia,Pinia 目前也已经是 vue 官方正式的状态库。适用于 vue2 和 vue3。可以简单的理解成 Pinia 就是 Vuex5。也就是说, Vue3 项目,建议使用Pinia,当然很多公司或者是项目由 vue2 转为 vue3 之后,由于习惯了使用 vuex ,所以说,在 vue3 当中继续使用 vuex 的,也不是少数,都知道就可以,根据实际情况来选择。
Pinia的来源
Pinia 是 Vue 的专属状态管理库,它允许你跨组件或页面共享状态。
Pinia (发音为 /piːnjʌ/,类似英文中的 “peenya”) 是最接近有效包名 piña (西班牙语中的 pineapple,即“菠萝”) 的词
什么是 Pinia
Pinia 是 Vue 的存储库,它允许您跨组件/页面共享状态。Pinia 的成功可以归功于他管理存储数据的独特功能,例如:可扩展性、存储模块组织、状态变化分组、多存储创建等。
Pinia的优点
Devtools 支持
- 追踪 actions、mutations 的时间线
- 在组件中展示它们所用到的 Store
- 让调试更容易的 Time travel
热更新
- 不必重载页面即可修改 Store
- 开发时可保持当前的 State
- 插件:可通过插件扩展 Pinia 功能 为 JS 开发者提供适当的 TypeScript 支持以及自动补全功能。
- 支持服务端渲染
基本使用store/counter.js
import {ref} from 'vue'
export const useCounterStore = defineStore('counter', () => {
const count = ref(0) //定义状态 count
function increment() { // 定义改变状态的方法
count.value++
}
// 导出状态与方法
return { count, increment }
})
基本使用main.js
import { createPinia } from 'pinia'
app.use(createPinia())
基本使用 (组件中使用)
// 导入仓库
import { useCounterStore } from '@/stores/counter'
// 生成仓库
const counter = useCounterStore()
// 更新仓库
counter.count++
counter.increment()
State-变更
除了用 store.count++ 直接改变 store,你还可以调用 $patch 方法
store.$patch({
count: store.count + 1,
age: 120,
})
你还可以调用 $patch 方法 ,引用类型
store.$patch((state) => {
state.items.push({ name: 'shoes', quantity: 1 })
state.hasChanged = true
})
State-替换
// 这实际上并没有替换`$state`
store.$state = { count: 24 }
// 在它内部调用 `$patch()`:
store.$patch({ count: 24 })
//or
pinia.state.value = {}
State-监听(存储到本地)
cartStore.$subscribe((mutation, state) => {
// import { MutationType } from 'pinia'
mutation.type // 'direct' | 'patch object' | 'patch function'
// 和 cartStore.$id 一样
mutation.storeId // 'cart'
// 只有 mutation.type === 'patch object'的情况下才可用
mutation.payload // 传递给 cartStore.$patch() 的补丁对象。
// 每当状态发生变化时,将整个 state 持久化到本地存储。
localStorage.setItem('cart', JSON.stringify(state))
}, { detached: true })
你可以在 pinia 实例上侦听整个 state。
watch(
pinia.state,
(state) => {
// 每当状态发生变化时,将整个 state 持久化到本地存储。
localStorage.setItem('piniaState', JSON.stringify(state))
},
{ deep: true }
)
计算
export const useCounterStore = defineStore('counter', () => {
const count = ref(0)
const doubleCount = computed(() => count.value * 2)
return { count, doubleCount }
})
访问其他store的actions
async fetchUserPreferences() {
const auth = useAuthStore()
if (auth.isAuthenticated) {
this.preferences = await fetchPreferences()
}
}
订阅actions

插件
function SecretPiniaPlugin() {
return { secret: 'the cake is a lie' }
}
const pinia = createPinia()
// 将该插件交给 Pinia
pinia.use(SecretPiniaPlugin)
// 在另一个文件中
const store = useStore()
store.secret // 'the cake is a lie'
插件-添加路由
mport { markRaw } from 'vue'
// 根据你的路由器的位置来调整
import { router } from './router'
pinia.use(({ store }) => {
store.router = markRaw(router)
})
插件-订阅
pinia.use(({ store }) => {
store.$subscribe(() => {
// 响应 store 变化
})
store.$onAction(() => {
// 响应 store actions
})
})
导航守卫中使用 store 的例子
router.beforeEach((to) => {
// ✅ 这样做是可行的,因为路由器在安装完之后就会开始导航。
// Pinia 也将被安装。
const store = useStore()
if (to.meta.requiresAuth && !store.isLoggedIn) return '/login'
})
更多请查询相关资料
Pinia 中文网:Pinia 中文文档

全部评论 (0)
还没有任何评论哟~
