【问题标题】:How can I pass data to nested components from Vue instance如何将数据从 Vue 实例传递给嵌套组件
【发布时间】:2018-02-02 12:34:48
【问题描述】:

我通过 AJAX 从 Vue 实例获取数据,我需要将该数据传递给组件。我现在正在学习 Vue.js 的工作原理,但我发现文档有点零碎......

这大概是我的代码:

<!DOCTYPE html>
<html lang="en">
    <meta charset="UTF-8">
    <title>mysite</title>
</head>
<body>

<div id="app">
    <parent-component></parent-component>
</div>

<template id="parent-component-template">
    <div id="the-template">
        <div class="the-list">
            <span is="sector-item" v-for="item in sectors" :sector="item"></span>
        </div>
        <button>Button</button>
    </div>
</template>

<template id="sector-item-template">
    <span>
        {{ sector.name }}
    </span>
</template>

<!-- Vue.js -->
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.4.2/vue.js"></script>

<script>
    Vue.component('parent-component', {
        template: '#parent-component-template'
    });

    Vue.component('sector-item', {
        props: ['sector'],
        template: '#sector-item-template'  
    });

    let app = new Vue({
        el: '#app',
        data: {
            sectors: [{
                'id': 1,
                'name': 'Industry'
            }]
        }
    });
</script>

</body>
</html>

我收到以下错误:

[Vue warn]: Property or method "sectors" is not defined on the instance but referenced during render. Make sure to declare reactive data properties in the data option.

我在哪里犯错了?

【问题讨论】:

标签: javascript vue.js frontend


【解决方案1】:

我认为您的代码不完整。我试图在下面的 sn-p 中模拟你想要做的事情:

Vue.component('parent-component', {
  props: ['sectors']
});

Vue.component('child-component', {
  props: ['item']
});

new Vue({
  el: '#app',
  data: {
    sectors: [
      {
        'id': 1,
        'name': 'Industry'
      },
      {
        'id': 2,
        'name': 'Education'
      }
    ]
  }
});
.the-list > div {
  padding: 5px;
  border: 1px solid gray;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.4.2/vue.js"></script>

<div id="app">
  <parent-component :sectors="sectors" inline-template>
    
    <div class="the-list">
      <child-component :item="sector" :key="sector.id" v-for="sector in sectors" inline-template>
        <div>
          <span v-text="item.name"></span>
          <button>Button</button>
        </div>
      </child-component>
    </div>
    
  </parent-component>
</div>

Vue 实例拥有属性sectors,我将此属性作为prop 传递给&lt;parent-component&gt;

现在&lt;parent-component&gt; 有一个名为sectors(它可能是另一个名称)的道具,它从主Vue 实例接收sectors 的值。我使用v-for 遍历了 parent-component prop 的所有项,将数组的每个项传递给&lt;child-component&gt;

&lt;child-component&gt; 有一个名为 item 的道具,我在其中传递了数组每个元素的值。

您可以了解更多信息,here免费

我希望这个答案能有所帮助。

【讨论】:

  • 非常有帮助。非常感谢! :)
猜你喜欢
  • 2018-11-12
  • 2017-02-27
  • 1970-01-01
  • 2017-09-12
  • 2017-04-17
  • 2018-02-15
  • 2019-03-28
  • 2020-07-22
相关资源
最近更新 更多