简体   繁体   中英

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 :)

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 }}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM