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

不使用vue-router时,Vue JS如何提取Laravel路由URL路径中的用户ID参数

可用的实现方案有两种,可根据你的项目情况选择:

方案1:纯前端解析URL路径(无需修改后端逻辑)

你可以直接通过浏览器原生API获取当前页面路径,拆分后匹配规则提取用户ID,适配固定格式的路由结构:

// Vue 2/Vue 3 选项式API通用写法
export default {
  data() {
    return {
      userId: null
    }
  },
  created() {
    // 拆分路径,过滤掉空字符串
    const pathSegments = window.location.pathname.split('/').filter(seg => seg)
    // 匹配路由中的user标识,后一段即为用户ID,比硬编码索引容错性更高
    const userPosition = pathSegments.findIndex(seg => seg === 'user')
    if (userPosition !== -1 && pathSegments[userPosition + 1]) {
      this.userId = Number(pathSegments[userPosition + 1])
    }
  }
}

如果是Vue3组合式API写法:

import { ref, onMounted } from 'vue'

const userId = ref(null)

onMounted(() => {
  const pathSegments = window.location.pathname.split('/').filter(seg => seg)
  const userPosition = pathSegments.findIndex(seg => seg === 'user')
  if (userPosition !== -1 && pathSegments[userPosition + 1]) {
    userId.value = Number(pathSegments[userPosition + 1])
  }
})

方案2:通过Blade模板传参(更稳定,优先推荐)

因为你的Vue组件是从Laravel Blade直接渲染的,可以直接在后端层把路由参数传给Vue组件,完全不需要前端解析路径,不会受路由前缀调整的影响:

  1. 先确认Laravel路由已声明参数:
// routes/web.php
Route::get('/admin/users/dashboard/user/{userId}/show', [UserDashboardController::class, 'index']);
  1. 控制器将参数传递给Blade视图:
// app/Http/Controllers/UserDashboardController.php
public function index($userId)
{
    return view('user.dashboard', compact('userId'));
}
  1. Blade模板渲染Vue组件时传入参数:
<!-- resources/views/user/dashboard.blade.php -->
<your-dashboard-component :user-id="{{ $userId }}"></your-dashboard-component>
  1. Vue组件内直接声明props接收即可:
export default {
  props: {
    userId: {
      type: Number,
      required: true
    }
  }
}

内容的提问来源于stack exchange,提问作者Martin M

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.29 23:45:02