So, I have a Vuex
state that looks like so:
state: {
keylist: ['key1', 'key2', 'key3'],
items: {
key1: {title: "First Item"},
key2: {title: "Second Item"},
key3: {title: "Third Item"}
}
}
And I have a list component, referenced from root like so:
<event-list :list="this.$store.state.keylist"></event-list>
The components is defined like so:
Vue.component('event-list', {
template: "<ul><li v-for='key in list'>{{ key }}</li></ul>",
props: {
list: {
type: Array,
required: true
}
}
})
Now, this all displays the key just fine.
But, of course, what I really want to do is use a component on each item, found by it's key. And that's where I am stuck. I have an item component like so:
Vue.component('event-list-item', {
template: "<h4>{{ item.title }}</h4>",
props: {
item: {
type: Object,
required: true
}
}
})
But I cannot figure out how to translate the key
in the parent component into an item
in the child component. This template barfs on the first curly brace:
<ul><li v-for='key in list'><event-list-item :item="this.$store.state.items.{{key}}"</li></ul>
And in any case, that doesn't look like the right solution! so What is the right one?
To me the first thing that comes to mind is that's your nested item has no place to be inserted anyway. You might want to have a look at slots for nesting components like that: https://v2.vuejs.org/v2/guide/components.html#Content-Distribution-with-Slots
Anyway, a few considerations:
In your use case you are better off having the list in the event list item and repeat just the element that you actually need, rather than retrieving it in a useless component that only wraps around another component. I mean:
Vue.component('event-list-item', { template: "<li v-for="item in list"><h4>{{ item.title }}</h4></li>
The store is considered the single source of truth also because it should be easier to access it from the directly impacted components, sparing you from having to hand down multiple props for several layers. Like you are doing. This base is kinda brittle for deeply nested components.
Keep in mind that each component has a different scope and they don't share a thing that's not explicitly passed.