Julian
Julian

Reputation: 613

Vuex: How can I pass a variable to a getter?

In a vue app I get an elementId from the URL to pass in to a vuex getter:

<template>
  <p>elementId: {{ elementId }}</p>
  <p>loadedElement: {{ loadedElement }}</p>
</template>

<script>
export default {
  data() {
    return {
      elementId: this.$route.params.id,
    };
  },
  computed: {
    loadedElement() {
      return this.$store.getters.getElementById(this.elementId);
    },
  },
};
</script>

Getter:

getElementById: (state) => (id) => {
  return state.elements.find(ele => ele.id === id)
},

Right now the page gets rendered like this:

enter image description here

However, when hardcode an elementId, it works:

<template>
  <p>elementId: {{ elementId }}</p>
  <p>loadedElement: {{ loadedElement }}</p>
</template>

<script>
export default {
  data() {
    return {
      elementId: 3,
    };
  },
  computed: {
    loadedElement() {
      return this.$store.getters.getElementById(this.elementId);
    },
  },
};
</script>

enter image description here

I don't understand what I'm doing wrong since getting the elementId from the route seems to work, but it is not passed into the getter function.

What am I doing wrong?

Upvotes: 0

Views: 351

Answers (1)

Decade Moon
Decade Moon

Reputation: 34306

Most likely this.$route.params.elementId is a string but your element IDs are numbers. Using === to compare a string and number will not match.

Try using == instead, or converting this.$route.params.elementId to a number:

data() {
  return {
    elementId: +this.$route.params.id,
  };
},

(Of course, maybe you want to do more error checking as part of this.)

Upvotes: 2

Related Questions