Last active
July 10, 2023 06:59
-
-
Save margauxflores/330fd791f8873c29554e5ac604525a69 to your computer and use it in GitHub Desktop.
Passing Data Through Vue Router
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# 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