javascript - Vue - 无法获取父组件数据

标签 javascript vue.js

我是 Vue 的新手,我正在尝试使用子组件的 props 获取父组件的数据,但我无法获取父组件的数据。

谁能告诉我该怎么做?

谢谢。

window.onload = () => {
  var vm = new Vue({
    el:'#app',
    data:{
      a:'aaa'
    },

    components:{
      'aaa':{
           data(){
             return {
               msg:"parent's component data1",
               msg2:"parent's component data2"
             }
           },
        template:'#aaa',
        component:{
          'bbb':{
            props:['m','myMsg'],
            template:'<h3>{{m}} <br> {{myMsg}}</h3>'
          }
        }
      }
    }
  })
}
<div id="app">
  <aaa></aaa>
</div>
<template id='aaa'>
  <h2>aaa-->{{msg}}</h2>
  <bbb :m='msg' :myMsg='msg2'></bbb>
</template>

最佳答案

你的 aaa组件的模板没有单个根元素。我添加了一个 <div> (见下文)。

此外,更重要的是,如果 Prop 是 myMsg使用 :my-msg 从父级传递它:

var vm = new Vue({
  el: '#app',
  data: {
    a: 'aaa'
  },
  components: {
    'aaa': {
      data() {
        return {
          msg: "parent's component data1",
          msg2: "parent's component data2"
        }
      },
      template: '#aaa',
      components: {
        'bbb': {
          props: ['m', 'myMsg'],
          template: '<h3>{{m}} <br> {{myMsg}}</h3>'
        }
      }
    }
  }
});
<script src="https://unpkg.com/vue"></script>

<template id="aaa">
  <div>
    <h2>aaa--->{{msg}}</h2>
    <bbb :m='msg' :my-msg='msg2'></bbb>
  </div>
</template>

<div id="app">
  <aaa></aaa>
</div>

关于javascript - Vue - 无法获取父组件数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49861188/

相关文章:

JavaScript 不会从特定数组列表中随机选择名称

vue.js - Nuxtjs 导入 vue-image-crop-upload 库时带来意外的标记 <

javascript - 如何在 vue js html 中根据时间显示 "Closed"或 "Open"?

javascript - 复选框按钮未与其他按钮内嵌

javascript - 如何在新标签页中打开 YouTube 嵌入式视频?

javascript - 如何使 href 在 jquery-bootgrid 基本插件中工作

javascript - 在将少量记录插入 Postgres 数据库后,Nodejs 应用程序使用 knex 中断

javascript - 是否可以为每个页面设置SSG和SSR?

javascript - Vue路由器: fetching data from server (asynchronously with ajax) does not update the view in component

javascript - 使用 Angular 指令初始化多个 jQuery 插件