Vue3.0+vite (5) 之 Pinia

本文介绍了Pinia作为Vue3的状态管理库,它轻量且易于使用,可替代Vuex。通过示例展示了如何设置和修改状态,强调了避免直接解构以保持响应性,并给出了getters的使用方法。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

Pinia 是 Vue 的存储库,它允许您跨组件/页面共享状态。 如果您熟悉 Composition API,您可能会认为您已经可以通过一个简单的 export const state = reactive({}). 这对于单页应用程序来说是正确的,但如果它是服务器端呈现的,会使您的应用程序暴露于安全漏洞。 但即使在小型单页应用程序中,您也可以从使用 Pinia 中获得很多好处

Pinia特别轻量级,十分简单的编写。将是替换Vuex的工具

首先下载依赖

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

main.js 中声明

import { createApp } from 'vue'
import App from './App.vue'
import {createPinia} from 'pinia'
const store = createPinia()

createApp(App).use(store).mount('#app') 

src 中新建文件夹 store 并新建 index.js 文件

import { defineStore } from 'pinia'

// 第一个参数是应用程序中 store 的唯一 id
export const useTestStore = defineStore('Test', {// other options...
}) 

我们在这里定义一个名为useTestStore的store,接下来声明 state,就是要存储的状态

import { defineStore } from 'pinia'

export const useTestStore = defineStore('Test', {state:()=>{return {current:1,age:26,}},//类似于computed 可以帮我们去修饰我们的值getters:{},//可以操作异步 和 同步提交stateactions:{setCurrent () {this.current++},changeCurrent(newCurrent){this.current = newCurrent}}
}) 

声明了两个变量,并且创建了两个方法放入actions

接下来直接调用

<script setup>
import {useTestStore} from '../store'
const Test = useTestStore()

const { current, age } = Test
const Add = () => {Test.current++//Test.setCurrent()
}
const Jian = ()=>{Test.current--
}
const change = ()=>{//在他的实例上有$patch方法可以批量修改多个值// Test.$patch({// current:200,// age:99// })//推荐使用函数形式 可以自定义修改逻辑// Test.$patch((state)=>{// state.current = 200;// state.age = 40// })//$state您可以通过将store的属性设置为新对象来替换store的整个状态//缺点就是必须修改整个对象的所有属性// Test.$state = {// current:10,// age:30// } Test.changeCurrent(123)
}
</script>

<template><div>pinia:{{ current }}--{{ age }}<button @click="Jian">-</button>current:{{Test.current}}<button @click="Add">+</button>age:{{Test.age}}<button @click="change">change</button></div>
</template>

<style lang="less" scoped>

</style> 

修改state,可以直接对里面的值,直接修改 类似于

Test.current++ 

或者$patch方法可以批量修改多个值

 Test.$patch({current:200,age:99
 }) 

当然也可以在使用 actions 中声明的方法。

对于在Pinia是不允许直接解构是会失去响应性的。上述例子中

const { current, age } = Test
...
<div>pinia:{{ current }}--{{ age }}
<div> 

按照这样解构,current,与age修改后,不会改变。所以如果想解构,我们可以用storeToRefs

import { storeToRefs } from 'pinia'
const Test = useTestStore()
const { current, age } = storeToRefs(Test) 

这样子数据就可以按照预期改变。

getters就相当于计算属性啦,举个简单例子

getters:{newAge:(state)=> `我的年龄${state.age}`
}, 

直接调用

const {newAge} = storeToRefs(Test)

<div>{{newAge}}
<div> 
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值