Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

vue.js passing data from parent single file component to child

Using single file architecture I'm trying to pass data (an object) from a parent component to a child:

App.vue

<template>
  <div id="app">
    <app-header app-content={{app_content}}></app-header>
  </div>
</template>

<script>
import appHeader from './components/appHeader'
import {content} from './content/content.js'

export default {
  components: {
    appHeader
  },
  data: () => {
    return {
      app_content: content
    }
  }
}
</script>

appHeader.vue

<template>
  <header id="header">
    <h1>{{ app_content }}</h1>
  </header>
</template>

<script>
export default {
  data: () => {
    return {
      // nothing
    }
  },
  props: ['app_content'],
  created: () => {
    console.log(app_content) // undefined
  }
}
</script>

Seems to be such a trivial task and probably the solution is quite simple. Thanks for any advice :)

like image 361
riccardolardi Avatar asked Aug 07 '16 11:08

riccardolardi


1 Answers

You're almost there.

In order to send the app_content variable from App.vue to the child component you have to pass it as an attribute in the template like so:

<app-header :app-content="app_content"></app-header>

Now, in order to get the :app-component property inside appHeader.vue you will have to rename your prop from app_component to appComponent (this is Vue's convention of passing properties). Finally, to print it inside child's template just change to: {{ appContent }}

like image 116
Ibrahim Avatar answered Nov 01 '22 18:11

Ibrahim