Home > Net >  How to set default value from url browser in vuejs
How to set default value from url browser in vuejs

Time:08-05

I have a URL: https://local.test/real-price?city_id=2

Vue template

<template>
   <ul>
      <li
          v-for="city in states"
          :key="city.id"
          :id="city.id"
          v-bind:
       >
          {{ 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>

Result not auto add class "active" when city_id=2

CodePudding user response:

This is because the city_id variable is a number in your code while it's a string in the url.

Try parsing it in your mounted

this.city_id = this.$route.query.city_id ? parseInt(this.$route.query.city_id) : 0

CodePudding user response:

Another way of solving this is to use ==

v-bind:
  • Related