Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Adding dynamic class names using vue.js

Tags:

vue.js

vuex

I've made a customizable flash message using Vue.js. This is working great but the next step is allow a dynamic class to be added to the component.

Flash.vue

<template>
  <transition name="fade">
    <div v-if="showMessage" :class="flash-container {{ styleClass }}">
      <p>{{ message }}</p>
      <p>{{ styleClass }}</p>
    </div>
  </transition>
</template>

<script>
  export default{
    methods: {
      clearMessage () {
        this.$store.commit("CLEAR_MESSAGE")
      }
    },
    computed: {
      message () {
        return this.$store.getters.renderMessage
      },
      showMessage () {
        return this.$store.getters.showMessage
      },
      styleClass () {
        return this.$store.getters.styleClass
      }
    },
  }
</script>

If I try to add it like this I get this error:

- invalid expression: Unexpected token { in

flash-container {{ styleClass }}

Raw expression: v-bind:class="flash-container {{ styleClass }}"

What am I missing here?

like image 677
Bitwise Avatar asked Aug 28 '26 18:08

Bitwise


1 Answers

Change it to this and it will work:

:class="[styleClass, 'flash-container']"

Another option would be to split the declarations between the dynamic and static ones:

class="flash-container" :class="styleClass"

Under the hood, the separate ones are joined on render.

This this link for more info: https://v2.vuejs.org/v2/guide/class-and-style.html

like image 146
webnoob Avatar answered Aug 30 '26 12:08

webnoob



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!