Unable to render a component in VueJS

0

I have the following component in VueJS, which I declare before the instance of Vue

Vue.component('list', {
    template: '
                <div>
                  <ul>
                  <li v-for="dato in datos">
                    <span v-if="dato.id <= 3">{{ dato.title }}</span>
                    <span v-else>
                     {{ dato.title }}
                    </span>
                  </li>
                </ul>
               </div>
               '
  })

Which I want to invoke in my HTML, in this way

<list></list>

But from the console I receive this error

  

"[Vue warn]: Property or method \" data \ "is not defined on the   instance but referenced during render. Make sure that this property is   reactive, either in the data option, or for class-based components, by   initializing the property. See:    link .

     

found in

     

--- >          "

I can not understand how to solve the problem, I found in a forum that I had to include all the information within a single element root and the recommendation was a div but it still marks me wrong

    
asked by element 29.12.2018 в 05:11
source

1 answer

3

The error appears because datos does not exist within the component.

If the data can be stored directly within the component this can be an alternative:

Vue.component('list', {
  data () {
    return {
      // datos se encuentra dentro del componente
      datos: [ 
        {id: 1, title: 'titulo 1'},
        {id: 2, title: 'titulo 2'},
        {id: 3, title: 'titulo 3'},
    ]
    }
  },
  template: '
    <div>
      <ul>
        <li v-for="dato in datos">
          <span v-if="dato.id <= 3">{{ dato.title }}</span>
          <span v-else>
            {{ dato.title }}
          </span>
        </li>
      </ul>
    </div>
    '
  })

var app = new Vue({
  el: '#app'
})

HTML

<div id="app">
  <list></list>
</div>

Or if, on the contrary, the data is in a "parent" component, you can pass the data using props :

JS

Vue.component('list', {
  props: ['datos'], // datos es pasado a través de este atributo 
  template: '
    <div>
      <ul>
        <li v-for="dato in datos">
          <span v-if="dato.id <= 3">{{ dato.title }}</span>
          <span v-else>
            {{ dato.title }}
          </span>
        </li>
      </ul>
    </div>
    '
  })

var app = new Vue({
  el: '#app',
  data () {
    return {
      datos: [
        {id: 1, title: 'titulo 1'},
        {id: 2, title: 'titulo 2'},
        {id: 3, title: 'titulo 3'},
    ]
    }
  },  
})

HTML

<div id="app">
  <list :datos="datos"></list>
</div>
    
answered by 29.12.2018 / 17:29
source