Vincent1989
Vincent1989

Reputation: 1657

Can't pass Vue data into Vue component

I can't seem to pass Vue data into Vue component from an inline template.

I'm getting this error instead:

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

Below is my example code that I'm using:

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>

Upvotes: 4

Views: 378

Answers (2)

Daniel Beck
Daniel Beck

Reputation: 21475

You're trying to use inline-template without including an inline template. inline-template replaces the template of the component with whatever is inside its DOM node; you're getting undefined because it's empty.

If you want to use inline-template:

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>

If you want to use data-item's 'template' instead, just don't include inline-template on the element:

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>

Upvotes: 7

miraj
miraj

Reputation: 586

you can use is attribute

   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>

Upvotes: 0

Related Questions