Home > other >  Conditional CSS proprety set in computed object doesn't evaluate on the browser
Conditional CSS proprety set in computed object doesn't evaluate on the browser

Time:10-22

I am trying to make the header element's height size to change depending on a criteria. I set the desired heights in a headerHeightClass inside a computed object but it doesn't seem to work.

<template>
  <header :>
    <div >
            <!--Some irrelevant html code -->
    </div>
  </header>
</template>
<script>
export default {
  name: "MainNav",
  components: {},
  data() {
    return {
      isLoggedIn: false,
    };
  },
  computed: {
    headerHeightClass() {
      return {
        "h-16": !this.isLoggedIn,
        "h-32": this.isLoggedIn,
      };
    },
  },
  methods: {
    loginUser() {
      this.isLoggedIn = true;
    },
  },
};
</script>

I also tried:

computed: {
    headerHeightClass() {
      return this.isLoggedIn? "h-32": "h-16",
    },
  },

The headerHeightClass appears as a simple string in the browser.

CodePudding user response:

You need to write it like this instead of using headerHeightClass as a string (remove ' ')

<template>
  <header :>
    <div >
            <!--Some irrelevant html code -->
    </div>
  </header>
</template>

This can also be written without using computed

<template>
  <header :>
    <div >
            <!--Some irrelevant html code -->
    </div>
  </header>
</template>

CodePudding user response:

You can give a try like this (Just for a demo purpose I used Vue 2 version) :

Vue.component('headerComponent', {
  props: ['msg'],
  template: '<p>{{ msg }}</p>'
});

var app = new Vue({
  el: '#app',
  data: {
    isLoggedIn: true
  }
});
.w-full {
  background-color: gray;
  width: 100%;
}
.text-sm {
  font-size: 12px;
}
.h-16 {
  height: 16px;
}
.h-32 {
  height: 32px;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.17/vue.js"></script>
<div id="app">
  <header-component
      msg="This is a header component"
      :>
  </header-component>
</div>

  • Related