You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在Pinia Store中获取当前路由名称以查询Firestore集合?

在Pinia Store中获取当前路由名称并赋值给变量的方法

方案1:Store内直接获取路由名称

如果希望Store自主处理路由状态,直接在Store文件中导入Vue Router即可实现:

  1. 在Store文件顶部导入useRouter(适配Vue 3 + Vue Router 4)
  2. 创建路由实例,通过router.currentRoute.value.name获取当前路由名称
  3. 将该值赋值给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,可按以下步骤操作:

  1. 在调用Store方法的组件中,用useRoute获取当前路由名称
  2. 调用getNotes时将路由名称作为参数传入
  3. 在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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.06 03:16:11