Home > Enterprise >  VueJs switch buttons color
VueJs switch buttons color

Time:06-29

Im new in vuejs and i need a example how to switch color between two buttons when click then. For example:when I click the white button it turns black and the other one turns white, and vice versa

CodePudding user response:

In your template:

<div  :>
  <div  @click="toggleButton()" />
  <div  @click="toggleButton()" />
</div>

In your setup (This is just a suggestion, you could also use a ref or something else; may differ by version.):

const state = reactive({
  oneIsActive: true,
});

function toggleButton() {
  state.oneIsActive = !state.oneIsActive;
}

Your SCSS (may differ a bit in pure css or sass):

.button-wrapper {
  .one {
    background: white;
  }
  .two {
    background: black;
  }
  &:not(.one-is-active) {
    .one {
      background: black;
    }
    .two {
      background: white;
    }
  }
}

CodePudding user response:

If I understand correctly, you want to have functionality similar to a radio button group, where if you click on one, you want the color of the other one to revert.

In order to do that, the buttons need to share state.

Where/how this state is shared can be implemented many different ways, but for this example I'll suggest it is stored in the parent component. The state can also be implemented using composition API, or options API, I will assume based on the level of experience that options may be a better fit.

<script>
export default {
  data() {
    return {
      selected: 0
    }
  },
}
</script>

<template>
  <button : @click="selected = 1">
    Button 1
  </button>
  
  <button : @click="selected = 2">
    Button 2
  </button>
</template>

<style>
  .red{
    background: red;
  }
</style>

example in vue SFC playground

  • Related