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

Vue Router如何根据URL的id参数条件显示对应开发盒子并隐藏其余内容

实现URL id参数控制右侧内容显隐的方案

1. 定义盒子唯一标识

先给5个对应盒子分别设置唯一的id值,比如box1、box2、box3、box4、box5,和URL参数的id取值一一对应。

2. 获取URL中的id参数

根据你项目的技术栈选对应的获取方式:

  • 用Vue Router的项目,直接从路由参数读取:
computed: {
  currentBoxId() {
    // 没有匹配参数时默认展示第一个盒子
    return this.$route.query.id || 'box1'
  }
}
  • 无路由的原生项目,通过URLSearchParams读取:
computed: {
  currentBoxId() {
    const urlParams = new URLSearchParams(window.location.search)
    return urlParams.get('id') || 'box1'
  }
}

3. 给盒子加显隐判断

在你循环生成盒子的代码里,增加v-show或者v-if匹配当前id:

<div 
  v-for="box in 你的盒子列表" 
  :key="box.id"
  v-show="currentBoxId === box.id"
  class="body col-md"
>
  <!-- 你原有盒子的内容 -->
  <b-row>
    <b-col md="12">
      <b-form-textarea v-model="qs.text" size="sm" id="textarea-auto-height" placeholder="Question" rows="2" max-rows="2"></b-form-textarea>
    </b-col>
    <b-col md="6">
      <label>A</label>
      <b-form-input v-model="qs.chooseA" placeholder="Enter choose 1"></b-form-input>
    </b-col>
    <b-col md="6">
      <label>B</label>
      <b-form-input v-model="qs.chooseB" placeholder="Enter choose 2"></b-form-input>
    </b-col>
    <b-col md="6">
      <label>C</label>
      <b-form-input v-model="qs.chooseC" placeholder="Enter choose 3"></b-form-input>
    </b-col>
    <b-col md="6">
      <label>D</label>
      <b-form-input v-model="qs.chooseD" placeholder="Enter choose 4"></b-form-input>
    </b-col>
    <b-col md="6">
      <b-form-file class="file" placeholder="Choose a file or drop it here..." drop-placeholder="Drop file here..." ></b-form-file>
    </b-col>
  </b-row>
</div>

如果盒子切换频率高推荐用v-show,仅通过CSS控制显隐性能更好;切换频率低可以用v-if,不匹配的盒子不会渲染到DOM中。

4. 左侧侧边栏链接配置

点击左侧链接时跳转带上对应的id参数即可:

  • Vue Router项目用router-link:
<router-link 
  v-for="box in 你的盒子列表" 
  :key="box.id"
  :to="{ query: { ...$route.query, id: box.id } }"
>
  {{ box.linkName }}
</router-link>

上面的写法会保留URL中已有的其他参数,避免参数丢失。

  • 原生项目用a标签:
<a v-for="box in 你的盒子列表" :key="box.id" :href="`?id=${box.id}`">
  {{ box.linkName }}
</a>

内容的提问来源于stack exchange,提问作者Youssef Ghonem

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.07 05:00:04