Reputation: 60058
I'm trying to work out how I can use a variable (prop) as part of an array map function.
Basically I have this code:
var result = this.$store.getters['example/store'].map(a => a.fixed_column)
and I want fixed_column
to be able to be a variable, allowing me to reuse this component in lots of places depending what column name is passed in as a prop.
I tried
.map(a => a.{this.category})
and other various syntax variations of that - but couldnt get it to work.
What I want to be able to do is something like this:
<my-component category="example_column"></my-component>
and have the array sum up example_column
This is my full vue component if needed:
<template>
<div>
<p>Pending count: {{ pending }}</p>
</div>
</template>
<script>
export default {
props: {
category: {},
},
computed: {
pending() {
var result = this.$store.getters['example/store'].map(a => a.fixed_column);
return result.reduce((a, b) => a + b, 0);
}
},
}
</script>
Upvotes: 0
Views: 2827
Reputation: 4732
Correct way to access object property dynamically would be via brackets notation.
But for that to work, you have to make sure that category
prop can be accessed inside the component. For that, valid prop declaration is required.
Here are essential parts for it to work:
props: {
category: {
type: String,
default: 'default_category',
}
},
computed: {
pending() {
const result = this.$store.getters['example/store'].map(a => a[this.category]);
return result.reduce((a, b) => a + b, 0);
}
},
Upvotes: 1
Reputation: 1
You could simply do it as follow :
var result = this.$store.getters['example/store'].map(a => a[this.category]);
and category
should be a string
Upvotes: 1