How to handle css with Vue

Asked

Viewed 172 times

-4

I have a question, I wish to manipulate the css of the element body(more specifically the font-size) using Vue.js only I don’t find a way to do this. What I wish is that when I press the button it uses a method that increases the value of the font-size.

<template>
  <div>
    <Header />

    <button @click="aumentaFont()" class="button">Aumenta Fonte</button>

    <section class="l100">
      <nuxt />
    </section>

    <Footer />
  </div>
</template>

<style>
html,
body {
  font-size: 1em;
}
</style>
  • So Matheus, did you look at the official documentation before you asked the question? Is there a session explaining about that.

  • Okay, but I don’t see where I can put that data in the body?

1 answer

0


Come on, my recommendation is to create style classes that you want to apply on the body for the proper size of font-size.

Ai in your Vue component you make the logic to apply the classes in the body dynamically, example:

In your Assets/css/main.css:

.small-font-size {
  font-size: 12px;
}
.medium-font-size {
  font-size: 16px;
}
.large-font-size {
  font-size: 20px;
}

Load this . css into your project, it does not need to be associated with any component.

Ai in its component responsible for changing font size:

<template>
  <div>
    <button type="button" @click="smaller" :disabled="isSmallest">Diminuir fonte</button>
    <button type="button" @click="bigger" :disabled="isBiggest">Aumentar fonte</button>
  </div>
</template>
<script>
export default {
  name: 'FontSizeController',
  data() {
    return {
      fontSize: 2 // vamos dizer que 2 é medium, 1 é small e 3 é large
    };
  },
  computed: {
     isSmallest({ fontSize }) {
       return fontSize == 1;
     }
     isBiggest({ fontSize }) {
       return fontSize == 3;
     }
  },
  methods: {
    smaller() {
      if (this.fontSize > 1) {
        this.fontSize--;
        this.updateBodyFontSize();
      }
    },
    bigger() {
      if (this.fontSize < 3) {
        this.fontSize++;
        this.updateBodyFontSize();
      }
    },
    updateBodyFontSize() {
      const body = document.querySelector('body');

      switch (this.fontSize) {
        case 1:
          body.classList.add('small-font-size');
          body.classList.remove('medium-font-size');
          body.classList.remove('large-font-size');
          break;
        case 2:
          body.classList.add('medium-font-size');
          body.classList.remove('small-font-size');
          body.classList.remove('large-font-size');
          break;
        case 3:
          body.classList.add('large-font-size');
          body.classList.remove('medium-font-size');
          body.classList.remove('small-font-size');
          break;
      }
    },        
  }
}
</script>

Browser other questions tagged

You are not signed in. Login or sign up in order to post.