Search code examples
javascripthtmlvue.jsbootstrap-vue

Hyperlinking table data from API with vue-router


I'm taking in and displaying data from an API (https://restcountries.com/), but I'm having trouble hyperlinking each table entry to its own page with the router-link tag. Nothing happens, no errors, no linked text.

<template>
    <div>
        <b-table responsive head-variant="dark" striped hover :items="countries" :fields="headings">
            <template #cell(name)="data">
                <router-link :to="{name: 'country', params: {country: country.name.official}}">
                    {{ data.value }}
                </router-link>
            </template>
        </b-table>
    </div>
</template>

<script>
import axios from '@/config'

export default {
    name: 'AllCountries',
    components: {},
    data() {
        return {
            headings: [
                {
                    key: 'name.common',
                    sortable: true
                },
                {
                    key: 'capital',
                    sortable: true
                },
            ],
            countries: []
        }
    },
    mounted() {
        axios.get('/all')
        .then(response => {
            console.log(response.data)
            this.countries = response.data
        })
        .catch(error => console.log(error))
    }
}
</script>

If I remove the .common from the key 'name', router-link can work, but it will display all variations of country name rather than just the one 'common' name that I want. Also if .common is removed, the router-link does not work as it's shown here I get errors such as:

"TypeError: Cannot read properties of undefined (reading 'name')" "Property or method "country" is not defined on the instance but referenced during render."

Though I don't get these errors with this exact router-link elsewhere, and 'name' wasn't defined in those files), the only way I've gotten the router-link to link is with these params: { id: data.item._id }(though it links to nothing (it tries to link to '/undefined?fullText=true'))


Solution

  • Params of the router-link should have been params: { country: data.item.name.official }}