无法将Vue数据传递到Vue组件中

4
我似乎无法从内联模板将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>


1
如果你已经设置了 template: "<li>{{food}}</li>",为什么还需要使用 inline-template - lmarqs
2个回答

7

您正在尝试使用 inline-template,但没有包含内联模板。 inline-template 会用其 DOM 节点内部的任何内容替换组件的 template;由于它为空,因此您会得到 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,只需在元素上不包含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>


0
你可以使用 is 属性
   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">
      <ol>
        <li is="data-item" v-bind:food="value"></li>
      </ol>
    </div>

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接