pinia中使用要比Vuex简单。Vuex中有state、mutations、getters、actions、modules五种, 而
pinia中只有state、getters、actions。写法上有些不同。还是相对Vuex简单的

安装
yarn add pinia # or with npm npm install pinia
main.js
import { createApp } from 'vue' import App from './App.vue' import {
createPinia } from 'pinia' const pinia = createPinia() createApp(App)
.use(pinia) .mount('#app')
在src下新建store/index.js

因为没有Vuex中的modules了,其实这个新建的index.js就相当于是一个模块了 ,有其他模块
可以继续创建,只要为每个模块指定唯一的ID就可以了(就是defineStore中第一个参数)

import { defineStore } from 'pinia' /** * 1. 定义并导出容器 * 参数1: 容器的 ID , 必须唯一, 将来
Pinia 会把所有的容器挂载到跟容器 * 参数2: 选项对象 * 返回值: 一个函数, 调用得到容器实例 */ export const
useIndexStore = defineStore('index', { /** * 类似于组件的data, 用来存储全局状态 * 1.
必须是函数,这样是为了在服务端渲染的时候避免交叉请求导致的数据状态渲染 * 2. 必须是箭头函数, 这是为了更好的 TS 类型推导 */ state: ()
=> { return { count: 100, quantity: 10 } }, /** * 类似于组件的computed, 用来封装计算属性,
有缓存的功能 */ getters: { // 接受一个可选参数 state 即 当前ID为index的Store实例 也可以用this 拿到
上面的state的状态值 countTotal(state) { return state.count * state.quantity } }, /** *
类似于组件的 methods 封装业务逻辑, 修改state * 通过 this 拿到上面 state的状态值 */ actions: {
countChange(val) { console.log(val,'actions中的参数--->>>>') this.count++
this.quantity++ // or // this.$patch({}) // this.$patch(state => {}) } } })
组件中使用 
<template> count: {{indexStore.count}} quantity: {{indexStore.quantity}}
countTotal: {{indexStore.countTotal}} <hr> count: {{count}} quantity: {
{quantity}} countTotal: {{countTotal}} <hr> <el-button type="primary"
@click="indexStoreChange">修改state数据</el-button> </template> <script setup>
import { useIndexStore } from '@/store' import { storeToRefs } from 'pinia' //
state、getters、actions 里面属性或者方法 都是通过 indexStore “点” 出来使用的 const indexStore =
useIndexStore() // 如果想将状态数据结构出来直接使用 必须引入storeToRefs(否则不是响应式) 来自于 pinia(类似于
reactive响应式,结构使用toRefs) const { count, quantity, countTotal } =
storeToRefs(indexStore) // 修改state中的数据 const indexStoreChange = () => { // //
方式一: 最简单的方式就是这样 // indexStore.count++ // indexStore.quantity++ // //
方式二:如果修改多个数据,建议使用 $patch 批量更新 // indexStore.$patch({ // count: indexStore.count
+ 1, // quantity: indexStore.quantity + 1 // }) // // 方式三(推荐都使用这个就好):
更好的批量更新的方式: $patch 一个函数 这种性能更好 // indexStore.$patch(state => { // state.count++
// state.quantity++ // }) // 方式四: 逻辑比较多的时候 可以状态到 actions 中 调用 actions中的方法处理
indexStore.countChange() } </script> <style scoped> </style>

技术
下载桌面版
GitHub
百度网盘(提取码:draw)
Gitee
云服务器优惠
阿里云优惠券
腾讯云优惠券
华为云优惠券
站点信息
问题反馈
邮箱:ixiaoyang8@qq.com
QQ群:766591547
关注微信