0

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>
3
  • What is the type of category prop? Commented Oct 26, 2018 at 0:55
  • did you try a[this.category]? Commented Oct 26, 2018 at 0:55
  • @aBiscuit - I added some info to the question. Basically category would be a string I can set on the component to allow me to reuse it. Commented Oct 26, 2018 at 0:57

2 Answers 2

1

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);
  }
},
Sign up to request clarification or add additional context in comments.

Comments

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.