Vue中使用router-link props跨组件传值失败求助
Vue路由组件间无URL暴露的数据传递解决方案
问题原因
你之前的写法错误在于:
router-link不存在props属性,这个用法是无效的- 未通过命名路由+params传参的方式传递数据,且路由配置未开启props接收模式
正确实现步骤及代码修改
1. 修改Comp1组件的router-link写法
使用命名路由的对象语法传递参数,避免URL暴露数据:
<template> <div> <div> Router linkoo <router-link :to="{ name: 'comp2', params: { user: user } }">Go to Comp2</router-link> </div> </div> </template> <script> export default { name: 'Comp1', data() { return { user: 'john' } } } </script>
2. 修改路由配置,开启props接收
给comp2路由添加props: true,这样路由组件会自动把params中的参数映射为组件props:
const routes = [ { name: 'comp1', component: comp1, path: '/' }, { name: 'comp2', component: comp2, path: '/comp2', props: true // 开启props模式 } ]
3. Comp2组件无需修改
你已经正确声明了props: ['user'],点击按钮时就能正常打印this.user的值了。
原理说明
- 通过
name指定路由而非直接写路径,确保路由匹配的准确性 params传递的数据不会出现在URL中,满足你不暴露数据的需求- 路由配置中
props: true会自动将路由params中的参数注入到组件的props中,无需手动在组件内获取$route.params
内容的提问来源于stack exchange,提问作者john miller
相关产品推荐
相关产品推荐

