6

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?

2 Answers 2

12

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

Sign up to request clarification or add additional context in comments.

Comments

5

If you use v-bind, you can't use mustache {{}}. So you can do something like this:

<div class="flash-container" :class="styleClass">
</div>

or

<div :class="`flash-container ${styleClass}`">
</div>

or

<div class="flash-container" :class={'styleClass': true}>
</div>

Read this https://v2.vuejs.org/v2/guide/class-and-style.html#Binding-HTML-Classes

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.