如何在Pinia Store中获取当前路由名称以查询Firestore集合?
在Pinia Store中获取当前路由名称并赋值给变量的方法
方案1:Store内直接获取路由名称
如果希望Store自主处理路由状态,直接在Store文件中导入Vue Router即可实现:
- 在Store文件顶部导入
useRouter(适配Vue 3 + Vue Router 4) - 创建路由实例,通过
router.currentRoute.value.name获取当前路由名称 - 将该值赋值给
thisRouteName变量
代码示例:
// 导入依赖 import { defineStore } from 'pinia' import { useRouter } from 'vue-router' import { onSnapshot, collection } from 'firebase/firestore' import db from '@/firebase/config' // 替换为你的Firebase配置路径 export const useNotesStore = defineStore('notes', { state: () => ({ notes: [], thisRouteName: '', userId: 'your-user-id' // 替换为实际用户ID的获取逻辑 }), actions: { async getNotes() { const router = useRouter() // 赋值当前路由名称 this.thisRouteName = router.currentRoute.value.name // Firestore查询逻辑 const getNotesSnapshot = onSnapshot( collection(db, 'users', this.userId, this.thisRouteName), (querySnapshot) => { const notes = [] querySnapshot.forEach((doc) => { notes.push({ id: doc.id, content: doc.data().content, date: doc.data().date }) }) this.notes = notes } ) } } })
方案2:从组件传入路由名称
如果希望路由状态由组件管理,再传递给Store,可按以下步骤操作:
- 在调用Store方法的组件中,用
useRoute获取当前路由名称 - 调用
getNotes时将路由名称作为参数传入 - 在Store的
getNotes方法中接收参数并赋值给thisRouteName
组件代码:
<script setup> import { useRoute } from 'vue-router' import { useNotesStore } from '@/stores/notes' const route = useRoute() const notesStore = useNotesStore() // 调用Store方法时传入路由名称 notesStore.getNotes(route.name) </script>
Store修改后的代码:
export const useNotesStore = defineStore('notes', { state: () => ({ notes: [], thisRouteName: '', userId: 'your-user-id' }), actions: { async getNotes(routeName) { // 接收组件传入的路由名称 this.thisRouteName = routeName const getNotesSnapshot = onSnapshot( collection(db, 'users', this.userId, this.thisRouteName), (querySnapshot) => { const notes = [] querySnapshot.forEach((doc) => { notes.push({ id: doc.id, content: doc.data().content, date: doc.data().date }) }) this.notes = notes } ) } } })
注意事项
- 确保你的路由配置中每个路由都设置了
name属性,比如{ path: '/notes', name: 'notes', component: Notes } - 若使用Vue 2 + Vue Router 3,语法会略有差异,需通过
this.$route.name访问路由名称,Pinia中需对应调整路由实例的获取方式
内容的提问来源于stack exchange,提问作者Brunno Vert
相关产品推荐
相关产品推荐

