Reputation: 403
Trying to wrap my head around components and I'm having a hard time translating the official vuejs.org guide examples (which largely use new Vue({...})
) to the module structure offered with a fresh Vue app generated with the CLI.
If I have something like
const products = {
'bat': '9.99',
'glove': '7.50',
'cleets': '12.50'
}
How do I 'load' that into a component?
Products.vue
<template>
<div>
<li v-for="product in products">
{{ product }}
</li>
</div>
</template>
<script>
export default {
name: 'Products',
data: function () {
products: ?? // <-- My understanding is the products data would be added here somehow?
}
}
</script>
And then, in the 'Home.vue' component, something like
<template>
<div>
<Products />
</div>
</template>
<script>
import Products from "@/components/Products.vue";
export default {
name: "Home",
components: {
Products,
},
};
</script>
Any pointers? Thanks for any help! And sorry if it's something that should be obvious, it's frustrating to not be able to figure out a rather basic concept to Vue.js :(
Per @A.khalifa's response I modified Products.vue
to the following
<script>
export default {
name: 'Products',
data: function() {
products: [{
'bat': '9.99',
'glove': '7.50',
'cleets': '12.50'
}]
}
}
</script>
That now returns the following errors
10:5 error Elements in iteration expect to have 'v-bind:key' directives vue/require-v-for-key
23:5 error 'products:' is defined but never used no-unused-labels
I'm not sure what to do about the v-bind:key
directive... As for products
am I not referencing it properly within the directive?
Upvotes: 0
Views: 1116
Reputation: 6853
You are supposed to return an object from your data
data: function () {
return {
products: {
'bat': '9.99',
'glove': '7.50',
'cleets': '12.50'
}
}
}
or
data() {
return {
products: {
'bat': '9.99',
'glove': '7.50',
'cleets': '12.50'
}
}
}
and on your template
<li v-for="(price, name) in products" :key="name">
{{ name }} = {{ price }}
</li>
Read more about components basic here: https://v2.vuejs.org/v2/guide/components.html#Base-Example
And using v-for
with object here: https://v2.vuejs.org/v2/guide/list.html#v-for-with-an-Object
Upvotes: 2