0

I have a global variable that is populated with an API call when a component is mounted. I also have a chart component that I would like to show if that variable is not null (i.e. has the request has finished and it has been populated).

At the moment to render the chart I am using this:

<template>
  <div class="container">

    <b-chart
        v-if="$store.state.lists[api_key] != null"
        :chartdata="$store.state.lists[api_key]"
        :options="options"
    />
  </div>
</template>

I have tried moving this check $store.state.lists[api_key] != null to computed or watch, to minimise the inline scripting, but I can't seem to get it to work. Would someone please show me how.

matt
  • 1,817
  • 14
  • 35

2 Answers2

1

Try this:

computed: {
    canShowChart() {
        return this.$store.state.lists[this.api_key] != null;
    }
}
<b-chart
    v-if="canShowChart"
    :chartdata="$store.state.lists[api_key]"
    :options="options"
    />
Nazaire
  • 175
  • 5
  • I could have sworn, I tried this and it did not work. But I have just tried again and it works fine. Thanks – matt Mar 01 '21 at 02:45
  • if i wanted to call a function if `canShowChart` becomes true. How would I go about that? – matt Mar 01 '21 at 03:03
  • @matt your probably right, i made some edits because i made a mistake when i first posted – Nazaire Mar 01 '21 at 03:39
  • you could watch the computed value `canShowChart` https://stackoverflow.com/questions/41067378/watching-computed-properties – Nazaire Mar 01 '21 at 03:40
1

Since null values are interpreted as "falsy", and assuming you have an "api_key" data variable, you can use it this way:

computed: {
    chartData() {
        return this.$store.state.lists[this.api_key]
    }
}
<template>
  <div class="container">
    <b-chart
        v-if="chartData"
        :chartdata="chartData"
        :options="options"
    />
  </div>
</template>