91人参与 • 2025-04-24 • Javascript
npm install pinia # 或 yarn add pinia
目的:引入pinia核心库,为状态管理提供基础支持。
在main.js中初始化并注入vue应用:
import { createapp } from 'vue'
import { createpinia } from 'pinia'
import app from './app.vue'
const app = createapp(app)
const pinia = createpinia()
app.use(pinia) // 关键!全局启用pinia
app.mount('#app')作用:创建pinia实例并与vue3应用集成,使所有组件可访问store。
使用composition api风格定义store(推荐):
// stores/counter.js
import { definestore } from 'pinia'
import { ref, computed } from 'vue'
export const usecounterstore = definestore('counter', () => {
// 1. 定义状态(相当于data)
const count = ref(0)
// 2. 定义计算属性(相当于getters)
const doublecount = computed(() => count.value * 2)
// 3. 定义操作方法(相当于actions)
function increment() {
count.value++
}
// 暴露状态与方法
return { count, doublecount, increment }
})核心要点:
definestore第一个参数为store唯一id(需全局唯一)ref/computed等响应式api管理状态在组件<script setup>中调用store:
<script setup>
import { usecounterstore } from '@/stores/counter'
const counterstore = usecounterstore() // 实例化store
</script>特性:store按需实例化,支持多组件复用且状态自动同步。
<template>
<div>
<p>当前计数:{{ counterstore.count }}</p>
<p>双倍计数:{{ counterstore.doublecount }}</p>
<button @click="counterstore.increment()">+1</button>
</div>
</template>响应式原理:直接访问store的属性会触发vue的响应式更新。
安装插件并配置:
npm install pinia-plugin-persistedstate
// main.js import piniapluginpersistedstate from 'pinia-plugin-persistedstate' pinia.use(piniapluginpersistedstate)
在store中启用:
definestore('counter', () => { /* ... */ }, {
persist: {
enabled: true, // 开启持久化
storage: sessionstorage, // 可选存储方式(默认localstorage)
paths: ['count'] // 指定需持久化的字段
}
})作用:浏览器刷新后自动恢复指定状态。
userstore.js、cartstore.js)vue devtools集成
安装浏览器插件后,可查看store状态变化历史与时间旅行调试。
自定义插件
可开发日志插件跟踪状态变更(示例见网页4的日志监控代码)。
通过以上步骤可实现:
对比vuex,pinia的函数式store语法更简洁,且与vue3的composition api深度契合,推荐作为vue3项目的首选状态管理方案。
以上为个人经验,希望能给大家一个参考,也希望大家多多支持代码网。
您想发表意见!!点此发布评论
版权声明:本文内容由互联网用户贡献,该文观点仅代表作者本人。本站仅提供信息存储服务,不拥有所有权,不承担相关法律责任。 如发现本站有涉嫌抄袭侵权/违法违规的内容, 请发送邮件至 2386932994@qq.com 举报,一经查实将立刻删除。
发表评论