Files
MyfronyProject/src/store/useExample.md
qingfeng1121 b042e2a511 feat: 添加Pinia全局状态管理并重构路由逻辑
添加Pinia作为全局状态管理工具,重构路由参数传递方式
移除URL中的动态参数,改为通过Pinia store传递数据
优化导航菜单样式和交互效果,修复路由激活状态问题
新增全局状态管理示例文档,说明基础使用方法
调整页面布局和样式,提升用户体验
2025-10-20 11:59:53 +08:00

4.9 KiB
Raw Blame History

Pinia 全局状态管理使用示例

1. 基础使用方法

在任意组件中使用全局状态

<template>
  <div>
    <h2>全局状态管理示例</h2>
    
    <!-- 显示全局数据 -->
    <div v-if="globalStore.hasValue('exampleData')">
      <p>从全局store获取的数据: {{ globalStore.getValue('exampleData') }}</p>
    </div>
    <div v-else>
      <p>全局数据尚未设置</p>
    </div>
    
    <!-- 设置全局数据 -->
    <el-input v-model="inputValue" placeholder="输入要存储的全局数据" />
    <el-button @click="setGlobalData">设置全局数据</el-button>
    <el-button @click="checkGlobalData">检查是否存在</el-button>
    <el-button @click="clearGlobalData" type="danger">清空全局数据</el-button>
  </div>
</template>

<script setup>
import { ref } from 'vue'
import { useGlobalStore } from '@/store/globalStore'

// 获取全局store实例
const globalStore = useGlobalStore()
const inputValue = ref('')

// 设置全局数据
const setGlobalData = () => {
  globalStore.setValue('exampleData', inputValue.value)
  ElMessage.success('数据已保存到全局状态')
}

// 检查数据是否存在
const checkGlobalData = () => {
  if (globalStore.hasValue('exampleData')) {
    ElMessage.info(`数据存在: ${globalStore.getValue('exampleData')}`)
  } else {
    ElMessage.warning('数据不存在')
  }
}

// 清空全局数据
const clearGlobalData = () => {
  globalStore.removeValue('exampleData')
  ElMessage.success('数据已从全局状态中移除')
}
</script>

2. 页面间数据传递示例

页面A - 设置数据

<script setup>
import { useGlobalStore } from '@/store/globalStore'
import { useRouter } from 'vue-router'

const globalStore = useGlobalStore()
const router = useRouter()

const navigateToPageB = () => {
  // 存储页面间需要传递的数据
  globalStore.setValue('sharedData', {
    id: 123,
    name: '测试数据',
    timestamp: Date.now()
  })
  
  // 跳转到页面B
  router.push('/page-b')
}
</script>

页面B - 获取数据

<script setup>
import { onMounted } from 'vue'
import { useGlobalStore } from '@/store/globalStore'

const globalStore = useGlobalStore()

onMounted(() => {
  // 检查并获取从页面A传递过来的数据
  if (globalStore.hasValue('sharedData')) {
    const data = globalStore.getValue('sharedData')
    console.log('从页面A接收的数据:', data)
    // 使用接收到的数据进行操作
  }
})
</script>

3. 批量操作示例

import { useGlobalStore } from '@/store/globalStore'

const globalStore = useGlobalStore()

// 批量设置多个键值对
globalStore.setMultipleValues({
  appConfig: {
    theme: 'dark',
    language: 'zh-CN'
  },
  userPreferences: {
    notifications: true,
    fontSize: 16
  },
  lastUpdated: new Date().toISOString()
})

// 获取所有全局数据
const allData = globalStore.getAllData()
console.log('所有全局数据:', allData)

// 清空所有数据
globalStore.clearAll()

4. 用户状态管理示例

<template>
  <div>
    <div v-if="globalStore.user">
      <h3>欢迎回来{{ globalStore.user.username }}</h3>
      <el-button @click="logout">登出</el-button>
    </div>
    <div v-else>
      <h3>请登录</h3>
      <!-- 登录表单 -->
    </div>
    
    <!-- 加载状态指示器 -->
    <el-loading v-loading="globalStore.loading" :text="'加载中...'">
      <!-- 内容区域 -->
    </el-loading>
  </div>
</template>

<script setup>
import { useGlobalStore } from '@/store/globalStore'

const globalStore = useGlobalStore()

const login = async (credentials) => {
  try {
    // 设置加载状态
globalStore.setLoading(true)
    
    // 模拟登录请求
    const response = await authService.login(credentials)
    
    // 保存用户信息到全局状态
globalStore.setUser(response.user)
    
    // 添加登录成功通知
globalStore.addNotification({
      type: 'success',
      message: '登录成功!'
    })
  } catch (error) {
    console.error('登录失败:', error)
  } finally {
    // 无论成功失败都清除加载状态
globalStore.setLoading(false)
  }
}

const logout = () => {
  // 清除用户信息
globalStore.setUser(null)
  
  // 添加登出通知
globalStore.addNotification({
    type: 'info',
    message: '您已成功登出'
  })
}
</script>

5. 注意事项

  1. 数据持久化默认情况下Pinia状态只在内存中存在页面刷新后会丢失。如果需要持久化可以考虑

    • 使用localStorage/sessionStorage结合Pinia插件
    • 使用Cookie存储关键信息
  2. 性能考虑:避免在全局状态中存储过大的数据,这可能会影响应用性能

  3. 类型安全如果使用TypeScript可以为store添加类型定义

  4. 模块化随着应用复杂度增加可以考虑将不同功能的数据分开存储到多个store中

  5. 调试Pinia提供了良好的开发工具支持可以通过Vue Devtools进行调试