Ayudh
Ayudh

Reputation: 1763

VueJS route params object

I am examining someone's code. They have the following in computed:

computed: {
        requireParams() {
            return {
                coach: this.coach,
                sid: this.sid
            };
        },
        coach() {
            return this.$route.params.coach || {};
        },
        sid() {
            return this.$route.params.sid || null;
        },
        avatar() {
            if (
                this.coach.profile_pic &&
                this.coach.profile_pic.indexOf("http") !== -1
            ) {
                return this.coach.profile_pic;
            } else {
                return "/images/_avatar.jpg";
            }
        }
}

Now in the html template code, coach is referred to multiple times like so

<p class="name">{{coach.last_name}}{{coach.first_name}}</p>

Could anyone explain how coach is an object being sent in route? I thought only strings could be sent in route like /path/:id would translate to /path/2 so $route.params would give {id: 2}.

But here coach is being accessed in route and it is apparently an object? I don't understand how this is possible

Upvotes: 0

Views: 140

Answers (1)

omerS
omerS

Reputation: 874

Well I am not sure if it is the right way to do it, but Vue lets you to pass an object in your router. If you have vuedevtools you can look at under vue $route section you will see: path, query, params, fullpath, name and meta. In params we can send an object.

For example your route will be like this:


const routes = [
  {
    path: '/',
    name: 'Home',
    component: Home
  },
  {
    path: '/about/:id',
    name: 'About',
    component: () => import(/* webpackChunkName: "about" */ '../views/About.vue')
  }
]

After lets create a button to push our data between routes.


<template>
  <div class="home">
   
   <button @click="sendObject">send my object</button>
    
  </div>
</template>

<script>

export default {
  name: 'Home',
  data() {
    return {
      myObj: {
        id: 1,
        name: "George",
        surname: "White",
        number: 123
      }
    }
  },
  methods: {
    sendObject() {
      this.$router.push({name: 'About', params: {id: this.myObj.id, comingItem: this.myObj}})
    }
  }
}
</script>


And finally lets take our item in other route like this:


<template>
  <div class="about">
    <h1>This is my object</h1>
    <div v-for="att in myItem" :key="att.id">
      <div> {{att}}</div>
    </div>
  </div>
</template>

<script>
export default {
  name: "About",
  data() {
    return {
      myItem : null
    }
  },
  created() {
    this.myItem = this.$route.params.comingItem
  }
}
</script>

Dom will be like:

1 George White 123.

Upvotes: 2

Related Questions