How to rewrite this code in Vue.js?

Asked

Viewed 33 times

0

funcao de vue js

wanted to rewrite that code on Vue.js

1 answer

1


First, welcome to Stackoverflow

When to your question, since Vuejs is very flexible, there are several ways to ask what you ask, but one of them may be:

<div :class="wrapClass">
    <button @click.prevent="toggleClass">Toggle class</button>
</div>

and in the script, something like

<script>
export default {
  data() {
    return {
      wrapClass: 'class1' // class inicial
    };
  },
  methods: {
    toggleClass() {
      this.wrapClass = this.wrapClass === 'class1' 
        ? ''       // remove a class
        : 'class1' // adiciona a class
    }
  }
}
</script>
  • :class="wrapClass when starting an attribute with : We’re telling Vue that the word inside quotes is a variable and not a string
  • @click.prevent="toggleClass" whereas @ is the same as v-on: we’re telling Vue that at the event click we want him to perform a method, and we add .prevent to prevent the browser from following the button’s "link"
  • the method is simple, and we only use a variable wrapClass which contains the original class, and when we perform the method toggleClass we change from one to the other value

here is an example in Codepen: https://codepen.io/balexandre/pen/poEGqyQ

  • You don’t need to use the .prevent if you use the <button> properly. By default o <button> takes as its default type="submit", so the form submission behavior you try to prevent... Simply use <button type="button" @click="toggleClass">...</button> so there won’t be this form submission behavior.

  • I understand, but he asked how to rewrite the code, and if he makes use of such a function, I also mentioned

Browser other questions tagged

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