Home > database >  Rotate image with @click in Vue2
Rotate image with @click in Vue2

Time:01-31

enter image description here

I have a refresh button on dashboard. I want to make it rotate 360 degrees. How can I rotate image with every click on a refresh button?

This is the code I tried, it only work twice click:

var vm = new Vue({
  el: '#app',
  data: {
    clicked: false,
  },
  methods: {
    rotation() {
      this.clicked = !this.clicked
    }
  }
})
.clicked {
  transform: rotate(360deg);
  transition: transform 0.5s ease-in-out;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.6.12/vue.js"></script>
<div id="app">
  <img 
    src="https://via.placeholder.com/100/09f.png/fff" 
    @click="rotation" 
    : 
    alt="refresh-icon-btn" 
  />
</div>

CodePudding user response:

Another approach is to use setTimeout to remove the class after the animation

var vm = new Vue({
  el: '#app',
  data: {
    clicked: false,
    rotationDuration: 500
  },
  methods: {
    rotation() {
      this.clicked = !this.clicked
      setTimeout(() => this.clicked = !this.clicked, this.rotationDuration)
    }
  }
})
.clicked {
  transform: rotate(360deg);
  transition: transform var(--rotation-duration) ease-in-out;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.6.12/vue.js"></script>
<div id="app">
  <img 
    src="https://via.placeholder.com/100/09f.png/fff" 
    @click="rotation" 
    : 
    :style="`--rotation-duration: ${rotationDuration}ms`"
    alt="refresh-icon-btn" 
  />
</div>

CodePudding user response:

You can just use a class binding to toggle the class on and off.

var vm = new Vue({
  el: '#app',
  data: {
    isClicked: false,
  },
  methods: {
    rotation() {
      this.isClicked = !this.isClicked
    }
  }
})
.image {
  transition: transform 0.5s ease-in-out;
}

.clicked {
  transform: rotate(360deg);
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.6.12/vue.js"></script>
<div id="app">
  <img 
    src="https://via.placeholder.com/100/09f.png/fff" 
    @click="rotation"
    
    : 
    alt="refresh-icon-btn" 
  />
</div>

CodePudding user response:

This could be one of the approach, have a inline style to toggle between 0 & 360 deg and have a constant class for transition.

var vm = new Vue({
  el: '#app',
  data: {
    deg: 0,
  },
  methods: {
    rotation() {
      this.deg  = 360;
    }
  }
})
.transition {
  transition: transform 0.5s ease-in-out;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.6.12/vue.js"></script>
<div id="app">
  <img src="https://via.placeholder.com/100/09f.png/fff" @click="rotation"  v-bind:style="{transform: 'rotate(' deg 'deg)'}" alt="refresh-icon-btn" />
</div>

  •  Tags:  
  • Related