当前位置: 首页 > news >正文

Vue3 之 Pinia 核心概念(八)

核心概念

State:这是你的应用程序的状态,是一个响应式的对象。
Getters:类似于 Vuex 中的 getters,它们是基于 state 的计算属性。
Actions:类似于 Vuex 中的 mutations 和 actions,它们用于改变 state。但与 Vuex 不同的是,在 Pinia 中,mutations 和 actions 被合并为一个概念,即 actions。
其他特性:Pinia 还支持插件、热重载、服务器端渲染等。

安装

npm install pinia  
# 或者使用 yarn  
yarn add pinia

main.js

import { createApp } from 'vue'  
import { createPinia } from 'pinia'  
import App from './App.vue'  const app = createApp(App)  
const pinia = createPinia()  app.use(pinia)  
app.mount('#app')

store/counter.js

import { defineStore } from 'pinia'  export const useCounterStore = defineStore('counter', {  // state  state: () => ({  count: 0,  }),  // getters  getters: {  doubleCount: (state) => state.count * 2,  },  // actions  actions: {  increment() {  this.count++  },  decrement() {  this.count--  },  // 你也可以在 actions 中使用其他 actions 或 getters  incrementBy(amount) {  this.count += amount  },  },  
})

App.vue

<template>  <div>  <p>Count: {{ counterStore.count }}</p>  <p>Double Count: {{ counterStore.doubleCount }}</p>  <button @click="counterStore.increment">Increment</button>  <button @click="counterStore.decrement">Decrement</button>  <button @click="counterStore.incrementBy(5)">Increment by 5</button>  </div>  
</template>  <script>  
import { useCounterStore } from './store/counter'  export default {  setup() {  const counterStore = useCounterStore()  return { counterStore }  },  
}  
</script>

扩展 Store

由于有了底层 API 的支持,Pinia store 现在完全支持扩展。以下是你可以扩展的内容:

为 store 添加新的属性
定义 store 时增加新的选项
为 store 增加新的方法
包装现有的方法
改变甚至取消 action
实现副作用,如本地存储
仅应用插件于特定 store

1. 插件 (Plugins)

插件是通过 pinia.use() 添加到 pinia 实例的。最简单的例子是通过返回一个对象将一个静态属性添加到所有 store。

import { createPinia } from 'pinia'// 创建的每个 store 中都会添加一个名为 `secret` 的属性。
// 在安装此插件后,插件可以保存在不同的文件中
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'

2. 持久化状态 (Persistence)
代码示例(使用第三方插件 pinia-plugin-persistedstate):

npm install pinia-plugin-persistedstate
import { createApp } from 'vue';  
import { createPinia } from 'pinia';  
import createPersistedState from 'pinia-plugin-persistedstate';  const pinia = createPinia();  // 使用插件  
pinia.use(createPersistedState({  storage: window.localStorage,  
}));  const app = createApp(/* ... */);  
app.use(pinia);  
// ...

3. 订阅状态变化 (Subscribing to State Changes)
Pinia 允许你订阅 Store 的状态变化,以便在状态更新时执行某些操作。这可以通过 pinia.state.subscribe 方法实现。
代码示例(在插件中使用):

// 插件中的代码  
app.pinia.state.subscribe((mutation, state) => {  // mutation 是一个对象,包含 type('direct' 或 'patch')和 key  // state 是 Store 的当前状态  console.log('State mutated:', mutation, state);  
});

4. 使用 TypeScript 进行类型安全
如果你在使用 TypeScript,Pinia 提供了强大的类型支持,确保你的代码是类型安全的。你可以为 state、getters 和 actions 提供类型定义。

代码示例(使用 TypeScript):

import { defineStore } from 'pinia';  interface CounterState {  count: number;  
}  export const useCounterStore = defineStore('counter', {  state: (): CounterState => ({  count: 0,  }),  // ...  
});

5. 访问其他 Store
在 Pinia 中,一个 Store 可以很容易地访问另一个 Store 的状态和方法。你可以直接在 Store 的 actions 中使用 useStore 函数来访问其他 Store。

代码示例:

import { defineStore } from 'pinia';  
import { useOtherStore } from './otherStore';  export const useCounterStore = defineStore('counter', {  // ...  actions: {  incrementAndDoSomethingElse() {  this.count++;  const otherStore = useOtherStore();  otherStore.doSomething();  },  },  
});

在组件外部使用 Store

1. 创建 Pinia 实例和 Store
首先,你需要在你的主入口文件(如 main.js 或 main.ts)中创建 Pinia 实例,并使用它创建你的 Store。

// main.js  
import { createApp } from 'vue'  
import { createPinia } from 'pinia'  
import App from './App.vue'  const app = createApp(App)  
const pinia = createPinia()  // 使用 Pinia  
app.use(pinia)  // 挂载应用  
app.mount('#app')  // 假设你有一个名为 useCounterStore 的 Store  
// import { useCounterStore } from './stores/counter'  
// 但在这里我们不会直接在 main.js 中使用它

2. 在组件外部使用 Store
示例:在路由守卫中使用 Store
假设你有一个名为 useUserStore 的 Store,用于管理用户状态,并且你想在路由守卫中检查用户是否已登录。

// router/index.js  
import { createRouter, createWebHistory } from 'vue-router'  
import { useUserStore } from './stores/user' // 假设你的 Store 在这里  
import pinia from '../main' // 引入 Pinia 实例(你可能需要根据你的项目结构来调整这个路径)  const router = createRouter({  history: createWebHistory(process.env.BASE_URL),  routes: [  // ...你的路由配置  ],  
})  // 在路由守卫中使用 Store  
router.beforeEach((to, from, next) => {  // 使用 pinia.useStore() 获取 Store 实例  const userStore = pinia.useUserStore()  // 假设有一个 isLoggedIn 的 getter 或 state 属性  if (to.meta.requiresAuth && !userStore.isLoggedIn) {  // 重定向到登录页面或执行其他操作  next('/login')  } else {  next()  }  
})  export default router

相关文章:

  • 零基础直接上手java跨平台桌面程序,使用javafx(五)TableView显示excel表
  • MySQL Hints:控制查询优化器的选择
  • python 实现各种数据分析方法
  • 解决用Three.js实现嘴型和语音同步时只能播放部分部位的问题 Three.js同时渲染播放多个组件变形动画的方法
  • MATLAB画图时添加标注显示有效数字的位数,可以编辑此函数
  • 使用Kotlin编写一个Http服务器
  • MEMS:Lecture 19 Wafer bonding package
  • Vue 3 中的状态管理:使用 reactive 函数实现组件间通信和状态管理
  • Flutter 应用加速之本地缓存管理
  • zookeeper、kakfa添加用户加密
  • k8s基础命令集合
  • Wake Lock API:保持设备唤醒的利器
  • Oracle阅读Java帮助文档
  • Pytorch-Padding Layers
  • 【定义通讯数据类型】LCM搭建系统通讯
  • gops —— Go 程序诊断分析工具
  • JAVA_NIO系列——Channel和Buffer详解
  • Lsb图片隐写
  • Netty 4.1 源代码学习:线程模型
  • PHP 7 修改了什么呢 -- 2
  • Web标准制定过程
  • 阿里云应用高可用服务公测发布
  • 产品三维模型在线预览
  • 从0实现一个tiny react(三)生命周期
  • 马上搞懂 GeoJSON
  • 山寨一个 Promise
  • 实习面试笔记
  • 树莓派 - 使用须知
  • 赢得Docker挑战最佳实践
  • mysql 慢查询分析工具:pt-query-digest 在mac 上的安装使用 ...
  • 微龛半导体获数千万Pre-A轮融资,投资方为国中创投 ...
  • ​【C语言】长篇详解,字符系列篇3-----strstr,strtok,strerror字符串函数的使用【图文详解​】
  • # 执行时间 统计mysql_一文说尽 MySQL 优化原理
  • #mysql 8.0 踩坑日记
  • (八)Flask之app.route装饰器函数的参数
  • (二十五)admin-boot项目之集成消息队列Rabbitmq
  • (附源码)计算机毕业设计大学生兼职系统
  • (论文阅读30/100)Convolutional Pose Machines
  • (四) Graphivz 颜色选择
  • (算法设计与分析)第一章算法概述-习题
  • (一)u-boot-nand.bin的下载
  • (转)MVC3 类型“System.Web.Mvc.ModelClientValidationRule”同时存在
  • .halo勒索病毒解密方法|勒索病毒解决|勒索病毒恢复|数据库修复
  • .NET Entity FrameWork 总结 ,在项目中用处个人感觉不大。适合初级用用,不涉及到与数据库通信。
  • .NET 常见的偏门问题
  • .NET6 开发一个检查某些状态持续多长时间的类
  • .net对接阿里云CSB服务
  • .net连接oracle数据库
  • .net图片验证码生成、点击刷新及验证输入是否正确
  • @property括号内属性讲解
  • @RequestMapping用法详解
  • [ C++ ] STL---string类的使用指南
  • [ 渗透测试面试篇 ] 渗透测试面试题大集合(详解)(十)RCE (远程代码/命令执行漏洞)相关面试题
  • [20150707]外部表与rowid.txt
  • [BZOJ1010] [HNOI2008] 玩具装箱toy (斜率优化)