Vue warn - Cannot use 'in' operator to search for '[object Array]'

Viewed 22873

Well,

I'm trying to do a project of an a Shopping cart with vue.js, and the browser Console is showing this error:

vue.common.js:576 [Vue warn]: Error in created hook: "TypeError: Cannot use 'in' operator to search for '[object Array]' in products"

// App.vue

<template>
  <div class="container">
      <div class="products">
        <div class="clearfix">
          <product v-for="product in products" :key="product"></product>
        </div>
      </div>
      <div class="shopping-cart">
        <shopping-cart></shopping-cart>
      </div>
  </div>
</template>

<script>

import ShoppingCart from './components/ShoppingCart.vue'
import Product from './components/Product.vue'

export default {
  created () {
    // dados mockados
    var dummy = [
      {id: 1, title: 'Name of Product 1', price: 40, image: 'product.png'},
      {id: 2, title: 'Name of Product 2', price: 90, image: 'product.png'},
      {id: 3, title: 'Name of Product 3', price: 10, image: 'product.png'},
      {id: 4, title: 'Name of Product 4', price: 20, image: 'product.png'}
    ];

    this.$set('products', dummy)
  },
  data () {
    return {
      products: []
    }
  },
  components: { Product, ShoppingCart }
}

</script>

What can I do?

I tried a lot of things and still without success =(

4 Answers

First of all you component name in template is "product" and also the key in for loop is also "product". Either you change Component name to suitable name like.

And you must have forgot to give a name(assign a name of component for tepmplate) to component which you imported. You cannot use imported component just like that without giving it reference name to use it in template.

components: { Product:productName, ShoppingCart: shoppingCart }

This way you use <product-name> </product-name> in template and so after that in for loop, the product in prodcuts will work.

Also products array should not work with this way. It should be in computed hook.

computed ={}

Or I should suggest you should directly asssign it in data()

I think the problem is with $set method, you need to specify the object as 1st parameter, see full doc here

so you need to do something like this:this.$set(this.products, dummy) also this will not give you 4 products in the v-for loop. I would suggest to assign the products directly in data()

you must use

this.products = dummy

instead of

this.$set('products', dummy)

and if you create your array in mounted () better than created () in your single app

Related