Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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>
like image 653
Vincent1989 Avatar asked Mar 04 '23 12:03

Vincent1989


1 Answers

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>
like image 166
Daniel Beck Avatar answered Mar 12 '23 03:03

Daniel Beck