Vue3 Vite项目动态路由链接失效,需实现交易对动态跳转
实现交易对动态跳转路由功能
问题背景
现有交易对列表需作为交易页面跳转链接,交易对数据来自AppMarkets.vue组件,其内部gotoMarketView跳转函数因失效被注释。该组件在App.vue中引入,当前App.vue的gotoMarket函数仅能静态跳转到指定交易对,需改造为根据用户选择的交易对动态生成路由并完成跳转。
解决方案步骤
1. 改造AppMarkets.vue的gotoMarketView函数
触发closeDialog事件时,将选中的交易对参数传递给父组件:
gotoMarketView: function(base, rel) { this.newmarket.base.ticker = base this.newmarket.rel.ticker = rel console.log("market selected going to trader view: " + this.newmarket.base.ticker + "/" + this.newmarket.rel.ticker); // 传递选中的base和rel参数给父组件 this.$emit("closeDialog", base, rel); },
2. 更新App.vue中AppMarkets组件的事件绑定
确保父组件能接收子组件传递的参数:
<AppMarkets v-on:closeDialog="gotoMarket" :key="componentKey" />
3. 改造App.vue的gotoMarket函数
根据接收的参数动态生成路由链接,以下是两种常见实现方式:
方式一:使用查询参数(Query)跳转
无需修改路由配置,直接通过query传递参数:
gotoMarket: function(base, rel) { console.log(this.componentKey) this.componentKey += 1 this.dialog = !this.dialog // 动态跳转带查询参数的路由 this.$router.push({ path: "/traderview", query: { base, rel } }); },
方式二:使用路径参数(Params)跳转
若需通过/traderview/{base}/{rel}格式跳转,需先在路由配置中定义参数:
// 路由配置示例(router/index.js) { path: '/traderview/:base/:rel', name: 'TraderView', component: TraderView }
再修改gotoMarket函数:
gotoMarket: function(base, rel) { console.log(this.componentKey) this.componentKey += 1 this.dialog = !this.dialog // 动态跳转带路径参数的路由 this.$router.push({ name: "TraderView", params: { base, rel } }); // 也可直接拼接路径字符串 // this.$router.push(`/traderview/${base}/${rel}`); },
4. 功能验证
选择交易对后,控制台会输出选中的交易对信息,页面将自动跳转到对应交易页面,路由参数会正确携带选中的base和rel值。
内容的提问来源于stack exchange,提问作者artistAhmed
相关产品推荐
相关产品推荐

