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

Vue.js从浏览器URL设置默认值:city_id=2时active类未自动添加

问题描述

我有一个URL:https://local.test/real-price?city_id=2

Vue模板代码如下:

<template>
   <ul>
      <li
          v-for="city in states"
          :key="city.id"
          :id="city.id"
          v-bind:class="{ active: (city.id === city_id) }"
       >
          {{ city.name }}
       </li>
  </ul>
</template>
<script>
export default {
   data: function() {
        return {
            states: [],
            city_id: 0,
        };
   },
   created() {
      this.states = [{id: 1, name: "City A"}, {id: 2, name: "City B"}, {id: 3, name: "City C"}];
   },
   mounted() {
      this.city_id = this.$route.query.city_id ? this.$route.query.city_id : 0
   },
}
</script>

问题:当URL中city_id=2时,对应的列表项未自动添加active类,请问如何从浏览器URL设置默认值并解决该问题?


问题原因

URL查询参数city_id的类型是字符串,而city.id是数字类型,使用全等运算符===比较时,类型不匹配导致条件不成立,因此无法添加active类。

解决方法

方法1:转换URL参数为数字类型

在mounted钩子中,将获取到的$route.query.city_id转为数字:

mounted() {
  this.city_id = this.$route.query.city_id ? Number(this.$route.query.city_id) : 0
}

方法2:使用非全等比较运算符

修改模板中的类绑定逻辑,用==代替===,允许类型隐式转换:

v-bind:class="{ active: (city.id == city_id) }"

方法3:通过路由props处理参数(推荐)

在Vue Router的路由配置中,直接将city_id转为数字并作为props传递给组件,同时设置默认值:

// 路由配置示例
{
  path: '/real-price',
  component: YourComponent,
  props: (route) => ({
    city_id: Number(route.query.city_id) || 0
  })
}

然后组件通过props接收参数,无需在mounted中处理:

export default {
  props: {
    city_id: {
      type: Number,
      default: 0
    }
  },
  data() {
    return {
      states: []
    };
  },
  created() {
    this.states = [{id: 1, name: "City A"}, {id: 2, name: "City B"}, {id: 3, name: "City C"}];
  }
}

内容的提问来源于stack exchange,提问作者Hai Truong IT

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.24 06:36:11