javascript - 无法将 Vue 数据传递给 Vue 组件

标签 javascript vue.js

我似乎无法将 Vue 数据从内联模板传递到 Vue 组件。

我收到了这个错误:

vue.min.js: Uncaught TypeError: Cannot read property 'type' of undefined

下面是我正在使用的示例代码:

Vue.component('data-item', {
  props: ['food'],
  template:"<li>{{food}}</li>"
})


var content = new Vue({
  el: '#content',
  data: {
    value: 'hello value!'
  }
})
<script src="//cdnjs.cloudflare.com/ajax/libs/vue/2.4.2/vue.min.js"></script>

<div id="content">
  <!-- this works
  <ol>
    <li>{{value}}</li>
  </ol>
  -->
  
  <!-- passing data from vue instance to component doesn't work -->
  <ol>
    <data-item  v-bind:food="value" inline-template></data-item>
  </ol>
  
</div>

最佳答案

您正在尝试使用 inline-template 而不包含内联模板。 inline-template 将组件的 template 替换为其 DOM 节点内的任何内容;你得到 undefined 因为它是空的。

如果你想使用内联模板:

Vue.component('data-item', {
  props: ['food'],
  template: "<li>This will be ignored in favor of the inline-template: {{food}}</li>"
})

var content = new Vue({
  el: '#content',
  data: {
    value: 'hello value!'
  }
})
<script src="//cdnjs.cloudflare.com/ajax/libs/vue/2.4.2/vue.min.js"></script>
<div id="content">
  <ol>
    <data-item v-bind:food="value" inline-template>
      <li>I am the inline template: {{food}}</li>
    </data-item>
  </ol>
</div>

如果您想使用 data-item 的"template",只需不要在元素上包含 inline-template 即可:

Vue.component('data-item', {
  props: ['food'],
  template:"<li>I am the component template: {{food}}</li>"
})

var content = new Vue({
  el: '#content',
  data: {
    value: 'hello value!'
  }
})
<script src="//cdnjs.cloudflare.com/ajax/libs/vue/2.4.2/vue.min.js"></script>
<div id="content">
  <ol>
    <data-item v-bind:food="value">
      I am the contents of the DOM node, which will be
      replaced by data-item's template.
    </data-item>
  </ol>
</div>

关于javascript - 无法将 Vue 数据传递给 Vue 组件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54693398/

相关文章:

javascript - 在已安装的 VueJS 中访问数据

javascript - JS : Separatedly get value from textareas with same class

javascript - 只为每个 Accordion 选择第一层的外部元素

javascript - 如何使用 Jest 测试组件是否正确计算数组长度

javascript - IE 11(Webpack、VueJS)上可能出现传播错误?

javascript - v-model 更改时 watch 不触发

javascript - 预期 T,在自定义对象类型的 Vue-Prop 中获取对象

php - 如何获取 Craigslist 列表并将它们放在我的网站上?

javascript - 如何对 Excel 电子表格进行排序 (KENDO UI)

javascript - 如何使用 Vue 在 div 中加载 Canvas ?