Search code examples
vue.jsvue-routerbulma

Vue JS access data from parent component


I am using the vue cli webpack and have an array of 'links' in my App.vue file. I want to figure out how I can use items from 'links' in my navbar.vue file. I have tried using props, the inherit property and passing it with :links="links" but nothing seems to work. Just to specify I am also using bulma the css library in case thats important.

App.vue:

<template>
  <div id="app">
      <navbar links="links"></navbar>

  </div>
</template>

<script>
import navbar from './components/navbar'

export default {
    name: 'app',
    components: {
        navbar
    },
    data () {
        return {
            links: [
                {name: 'Link 1', url: '#'},
                {name: 'Link 2', url: '#'}
            ]
        }
    }
   }
</script>

navbar.vue:

<template>
    <nav class="navbar has-shadow">
        <div class="navbar-menu">
            <a class="navbar-item">
                {{brand}}
            </a>
            <a class="navbar-item" v-for='link in links'>
                {{link.name}}
            </a>
        </div>
    </nav>
</template>

<script>
    import app from '../App'

    export default {
        name: 'navbar',
        inherit: true,
        data () {
            return {
                brand: 'Vue Website',
            }
        },

    }
</script>

I am pretty certain I have checked all methods I could find online but none of them worked or I could work out how to use them, if anyone could help me I would greatly appreciate it. :)


Solution

  • You need to declare links as a prop in navbar.vue, otherwise Vue will ignore it:

    export default {
        name: 'navbar',
        props: ['links'], // declare links as a prop
        data () {
            return {
                brand: 'Vue Website',
            }
        },
    }
    

    Then in the parent you can use it:

    <navbar :links="links"></navbar>
    

    See: https://v2.vuejs.org/v2/guide/components.html#Props