【问题标题】:vue.js passing data from parent single file component to childvue.js 将数据从父单文件组件传递给子组件
【发布时间】:2016-12-13 07:34:06
【问题描述】:

我尝试使用单文件架构将数据(对象)从父组件传递给子组件:

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>

似乎是一项微不足道的任务,而且解决方案可能很简单。感谢您的任何建议:)

【问题讨论】:

    标签: javascript ecmascript-6 vue.js


    【解决方案1】:

    你快到了。

    为了将 app_content 变量从 App.vue 发送到子组件,您必须将其作为模板中的属性传递,如下所示:

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

    现在,为了在 appHeader.vue 中获取 :app-component 属性,您必须将 prop 从 app_component 重命名为 appComponent(这是 Vue 传递属性的约定)。 最后,要在孩子的模板中打印它,只需更改为:{{ appContent }}

    【讨论】:

    • 谢谢,但遗憾的是,它仍然没有在子组件中呈现...
    • 您能否在两个组件中,在 ready() 方法上执行 console.log 并确保 this.app_content 确实包含某些内容?
    • 在两个组件的 ready() 方法中,即使是“this”,我也会得到“未定义”
    • ...虽然数据在呈现的 html 属性中显示为 [Object object]
    • 尝试在 appHeader.vue 中将变量更改为 appContent,因此它将是 props: ['appContent'] 和 {{ appContent }} 并且在 App.vue 中从 app-content={{app_content}} :app-content="app_content" 为在我的第一篇文章中。
    猜你喜欢
    • 2020-11-01
    • 2021-12-24
    • 2017-06-10
    • 2020-07-23
    • 1970-01-01
    • 2020-01-16
    • 1970-01-01
    • 2017-01-05
    • 2019-10-05
    相关资源
    最近更新 更多