Vue.js如何从现有数组动态取值并传递路由查询参数
Vue.js动态调用数组值实现API请求与路由参数传递
核心问题修复:路由参数类型不匹配
$route.params.id 默认为字符串类型,和数组中数字类型的id用===匹配会失败,导致无法获取对应数组条目,先修正计算属性:
// User.vue computed 调整 computed: { user () { const targetId = Number(this.$route.params.id) return this.lists.find(item => item.id === targetId) } }
实现mounted中拼接字符串发起API调用
新增mounted逻辑,加非空判断避免匹配不到条目时报错:
// User.vue 新增mounted mounted () { if (!this.user) return // 拼接要求的格式 const reqUrlSegment = `${this.user.book}/${this.user.pen}` // 此处替换为实际API调用逻辑 console.log('发起请求,拼接路径:', reqUrlSegment) }, // 若要支持路由id变化时自动重新请求,新增watch监听 watch: { user (newVal) { if (newVal) { const reqUrlSegment = `${newVal.book}/${newVal.pen}` console.log('路由更新后重新请求:', reqUrlSegment) } } }
实现点击路由传递pen、gap为query参数
修改router-link的to配置,直接从计算属性user中取值:
<!-- User.vue template 调整 --> <template> <!-- 加v-if避免user未加载完成时报错 --> <div v-if="user"> <router-link :to="{ name: 'BookWithID', query: { pen: user.pen, gap: user.gap } }"> {{ user.book }} </router-link> </div> </template>
额外路由配置优化
当前路由配置中两个路由path均为/,会优先匹配第一个,建议调整BookWithID的路径避免匹配异常:
// 路由配置修改 const router = new VueRouter({ routes: [ { path: "/", name: "User", component: HelloWorld }, // 单独设置图书详情页路径 { path: "/book-detail", name: "BookWithID", component: book }, { path: "/:id", name: "UserWithID", component: HelloWorld } ] });
内容的提问来源于stack exchange,提问作者T dhanunjay
相关产品推荐
相关产品推荐

