vue.jsvuejs2computed-values

How to set up a computed var in Vue to change the vue-bootstrap badge variant color


I am attempting to set up a computed var in Vue to set the variant of a bootstrap badge tag <b-badge> depending on data being returned from a JSON file.

I set up the response returned from the JSON file to be passed to an array called configData. I then set up the computed var in my Vue component to look like this:

computed: {
   dynamicColor() {
      return this.configData.permission === "Env" ? "primary" : "success"
   }
}

Inside the computed var, when the permission property is set to "Env", then the variant property in b-badge tag...

<b-list-group v-for="data in configData" :key="data.id">
    <b-list-group-item>
        <div>
            <h5><b-badge pill variant="\(dynamicColor)">{{ data.permission }}</b-badge></h5>
        </div>
    </b-list-group-item>
</b-list-group>

...will be set to "primary". Otherwise, if the permission property is set to another value in the JSON, then variant will be set to "success".

Here is the full component:

<template>
    <div id="config">
        <h3><b-icon icon="wrench"></b-icon> CONFIG</h3>
        <b-list-group v-for="data in configData" :key="data.id">
            <b-list-group-item>
                <div>
                    <h5><b-badge pill variant="\(dynamicColor)">{{ data.permission }}</b-badge></h5>
                </div>
            </b-list-group-item>
        </b-list-group>
    </div>
</template>

<script>
import axios from 'axios'

export default {
    name: 'Config',
    data() {
        return {
            configData: []
        }
    },
    created() {
        this.getConfigData()
    },
    computed: {
        dynamicColor() {
            return this.configData.permission === "Env" ? "primary" : "success"
        }
    },
    methods: {
        getConfigData() {
            axios
            .get('data_config.json')
            .then(response => (this.configData = response.data))
        }
    }
}
</script>

I'm not sure how to configure variant in the b-badge tag to receive the computed var. I tried adding "\(dynamicColor)" to variant, but this did not work.

How can I configure variant to receive the computed var? Or is there another way to handle dynamic coloring for the badge based on data returned from JSON?


Solution

  • As with any other bound attribute in Vue, the syntax is the following:

    <b-badge pill :variant="dynamicColor">{{ data.permission }}</b-badge>