Search code examples
vue.jsvuetify.jscomputed-properties

Use computed property to bind a style based on Vuetify's Viewport breakpoints


Working with VueJS and trying to style some text based on Vuetify's viewport breakpoints I have achieved this by binding the style to a condition like this:

:style="$vuetify.breakpoint.name === 'xs' ? { 'font-size': '1.5rem !important' }: { 'font-size': '2.5rem !important' }" 

however I would like to use computed property instead just to make it cleaner and according to Vuetify's docs this can be achieved using breakpoint object however I can't get it to work for some reason

I've looked at this discussion and trying to copy the answer from @raina77ow but not too sure what I'm doing wrong.

below is my code; I'm trying to style the h3 element inside v-card-title

<template>
  <div>
    <section>
      <v-layout>
        <v-flex xs12 sm10 offset-sm1>
          <v-card flat width="auto">
            <v-card-title primary-title>
              <h3
                class="text-xs-center headline mb-0"
                :style="fontSize"
              >
                Some Header here
              </h3>
              <div class="text-xs-center pa-5 mx-5">{{ card_text }}</div>
            </v-card-title>
          </v-card>
        </v-flex>
      </v-layout>
    </section>
  </div>
</template>

<script>
export default {
  computed: {
    fontSize() {
      switch (this.$vuetify.breakpoint.name) {
        case "xs":
          return "1.5rem !important";
        default:
          return "3rem !important";
      }
    }
  },
  data() {
    return {
      card_text:
        "Lorem ipsum dolor sit amet, brute iriure accusata ne mea."
    };
  }
};
</script>

Looking at Vuejs devtool I can see the computed property value changing as intended but just can't figure out why it's not being applied to CSS

Can someone tell me what am I doing wrong please!


Solution

  • Looks like the computed property isn't returning a full style specification. So you could either change the computed function

    case "xs":
        return {"font-size": "1.5rem !important"};
    default:
        return {"font-size": "3rem !important"};
    

    or change how it's being used

    :style="{'font-size': fontSize}"