Skip to content

Instantly share code, notes, and snippets.

@margauxflores
Last active July 10, 2023 06:59
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save margauxflores/330fd791f8873c29554e5ac604525a69 to your computer and use it in GitHub Desktop.
Save margauxflores/330fd791f8873c29554e5ac604525a69 to your computer and use it in GitHub Desktop.
Passing Data Through Vue Router
# Use case:
# I have a route where there's an ID parameter and I want to be able to pass data through Vue Router.
# Code setup is Vue + TypeScript using vue-class-component
# Home.vue template section
# This list is rendered after fetching data from an API call.
<template>
<li v-for="item in items" :key="item.id" @click.prevent="goToItem(item)">...</li>
</template>
# Home.vue script section
# When programmatically navigating to the route, it passes an ID and the item data object as paramaters.
<script lang="ts">
import { Component, Prop, Vue } from 'vue-property-decorator';
@Component({})
export default class ItemView extends Vue {
goToItem(item: Item): void {
this.$router.push({
name: 'item',
params: { id: item.id, itemData: item },
});
}
}
</script>
# router/index.ts's routes section
const routes: Array<RouteConfig> = [
{
path: '/',
name: 'Home',
component: Home,
},
{
path: '/item/:id',
name: 'item',
component: ItemView,
props: true,
},
];
# ItemView.vue script section
<script lang="ts">
import { Component, Prop, Vue } from 'vue-property-decorator';
@Component({})
export default class ItemView extends Vue {
@Prop() readonly itemData!: Item;
}
</script>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment