I’m learning Vue JS and I am creating my components. I’m stuck on an issue.
I would like to have my component taking in params an array of object like that :
JavaScript
x
18
18
1
data() {
2
return {
3
items: [
4
{
5
text: 'Admin',
6
href: '#'
7
},
8
{
9
text: 'Manage',
10
href: '#'
11
},
12
{
13
text: 'Library',
14
active: true
15
}
16
]
17
}
18
So, I tried to implement my component with props :
JavaScript
1
6
1
props: {
2
items: {
3
type: Array,
4
required: true
5
}
6
However, I have no idea how to say that : if items does not contains active key, then it should have a false default value.
If you have any advices/links or explanations, I will be very grateful to you.
Advertisement
Answer
You can make a computed
property which will fill-in those active: false
by default, and override it with the provided items:
JavaScript
1
12
12
1
props: {
2
items: {
3
type: Array,
4
required: true
5
}
6
},
7
computed: {
8
normalizedItems() {
9
return this.items.map(x => ({ active: false, x }));
10
}
11
}
12
You would then use normalizedItems
in your template instead of items