0

I am trying to import an array of objects from another JS file into a Vue component and let it render a card based on the object's properties. The import is working as I've logged it in the console and its returned the array, but when I try to assign it to an already existing array it throws TypeError: Cannot set property 'products' of undefined. Also, console.log(this.products) returns nothing but also doesn't throw an error. Below is my Products.vue component

<template>
<div>
    <header>
        <h1> Products </h1>
        <br>
        <h3> Browse All Our Products </h3>
    </header>
    <section>
        <div v-for='item in products' v-bind:key='item.name' class="product">
            <h3>{{ item.name }}</h3>
            <div>
            <img :src="item.img" />
            </div>
            <p>{{ item.desc }}</p>
            <p>{{ item.modelNum }}</p>
        </div>
    </section>
</div>
</template>

<style scoped src='../assets/products.css'></style>

<script>
    import { productList } from '../assets/db.js';

    export default {
    name: 'Products',
    data: function() {
        return {
            products: [],
            importList: productList,
        };
    },
    created: () => {
        this.products = productList;
        //console.log(products);
    }
}
</script>
Jacob Bruce
  • 55
  • 2
  • 10

2 Answers2

1

don't use Arrow function, just change it like this:

created: function() {
        this.products = productList;
        //console.log(products);
    }

Vue will bind this in data,method,mounted,computed...

yuhengshen
  • 91
  • 3
  • Thank you, this worked perfectly. Can you explain how, as it doesn't make sense to me since it's basically shorthand – Jacob Bruce May 27 '20 at 05:57
  • @JacobBruce [Use arrow function in vue computed does not work](https://stackoverflow.com/questions/42971081/use-arrow-function-in-vue-computed-does-not-work) – yuhengshen May 28 '20 at 07:07
1

should modify u code:

created: () => {
}
created () {
}