[Vuejs]-Vue.js Use a component within another on page via routes

0👍

Placement is everything… In my file called ProductList.vue I kept importing the component and then trying to add <ShoppingCart /> right after the </div> and before the </template> tags, when doing that I was receiving an error, I decided to try moving the <ShoppingCart /> tag right inside the </div> and it started working…

ProductList.vue

<template>
    <div>
        <h1>Product List</h1>
        <img v-if="loading" src="https://i.imgur.com/JfPpwOA.gif" />
        <ul v-else>
            <li v-for="product in products">
                {{product.title}} - {{product.price}} - {{product.inventory}}
                <button @click="addProductToCart(product)">Add to cart</button>
            </li>
        </ul>
        <ShoppingCart />
    </div>
</template>

<script>
    import ShoppingCart from '@/components/ShoppingCart'
    export default {
        name: 'ProductList',
        components: {
            ShoppingCart
        },
        data () {
            return {
                loading: false
            }
        },
        computed: {
            products () {
                return this.$store.getters.availableProducts
            }
        },
        methods: {
            addProductToCart (product) {
                this.$store.dispatch('addProductToCart', product)
            }
        },
        created () {
            this.loading = true
            this.$store.dispatch('fetchProducts')
                .then(() => this.loading = false)
        }
    }
</script>

<style scoped>
    ul {
        list-style-type: none;
    }
</style>

Leave a comment