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>
4

3 回答 3

1

不要使用箭头函数,只需像这样更改它:

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

Vue将绑定this在数据、方法、安装、计算...

于 2020-05-27T03:28:46.053 回答
1

应该修改你的代码:

created: () => {
}
created () {
}
于 2020-05-27T03:30:50.887 回答
-1

好的,首先您已将importList所有进口产品分配给变量。因此,在created()方法中您可以将其写为this.products = this.importList,我认为这应该可以解决您的问题。试试看!

于 2020-05-27T03:24:37.573 回答