Rotate image in Vue3 using @click

I have a dashboard with a refresh button that I want to rotate 360 degrees every time it is clicked. How can I achieve this rotation effect on the image with each click of the refresh button?

Below is the code snippet I have been working on, but it only rotates the image twice when clicked:

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" 
    :class="{ clicked }" 
    alt="refresh-icon-btn" 
  />
</div>

Answer №1

One interesting approach is using an inline style to toggle between 0 and 360 degrees, along with a constant class for transition effects.

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

Answer №2

To switch the class on and off, you can make use of a class binding.

const app = new Vue({
  el: '#app',
  data: {
    isClicked: false,
  },
  methods: {
    toggleClass() {
      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="toggleClass"
    class="image"
    :class="{ clicked: isClicked }" 
    alt="refresh-icon-btn" 
  />
</div>

Answer №3

To achieve the same result, one can also utilize the setTimeout function to eliminate the class post-animation.

const app = new Vue({
  el: '#app',
  data: {
    clicked: false,
    rotationDuration: 500
  },
  methods: {
    rotate() {
      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="rotate" 
    :class="{ clicked }" 
    :style="`--rotation-duration: ${rotationDuration}ms`"
    alt="refresh-icon-btn" 
  />
</div>

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

What could be causing my Vue application to not launch after executing `npm run serve`?

These past 24 hours have been a struggle for me. I recently embarked on the journey of learning Javascript, and my choice of JS framework was Vue JS. However, when I run npm run serve, my Vue JS app bombards me with numerous errors that seem to make no se ...

What steps should I follow to incorporate channel logic into my WebSocket application, including setting up event bindings?

I'm currently tackling a major obstacle: my very own WebSocket server. The authentication and basic functionality are up and running smoothly, but I'm facing some challenges with the actual logic implementation. To address this, I've create ...

CSS code for targeting specific screen sizes in the Bootstrap grid system

I'm not an expert in styling, but I often use Bootstrap for small projects. Currently, my main challenge lies within the grid system. With one monitor at a 1920x1080 resolution and another at 1366x768, I find myself wanting to adjust the grid system b ...

What steps should be taken to retrieve the contents of a file that has been chosen using the browse

You have successfully implemented a browse button that allows the user to navigate the directory and choose a file. The path and file name are then displayed in the text element of the Browse button complex. Now, the question arises - how can I extract dat ...

Switch the position of the Refer a friend button and the name button to the right

I am seeking assistance to align two buttons to the right. const getFullName = () => { if (authContext.user.first_name) { return `${authContext.user.first_name} ${authContext.user.last_name}`; } return authContext.use ...

Discovering a way to capture the space bar event in a number input field with JavaScript

Is there a way to capture space bar input with an onchange event in JavaScript? <html> <head> <script type = "text/javascript"> function lala(aa){ console.log(aa + " dasda"); } </script> </head> <body> <input ty ...

How does assigning a checkbox's value as 'undefined' result in the addition of ng-invalid?

I'm facing an issue with a checkbox in my Angular project. The checkbox has a false value of undefined, and even though it's not marked as required, the form doesn't validate when I check and uncheck it. This is because the class ng-invalid ...

Material-UI React is unable to identify the `underlineStyle` property on a specific HTML element

I tried implementing a custom style to change the underline color of a material-UI TextField element, following an example I found. http://www.material-ui.com/#/components/text-field Unfortunately, when I attempt to add my own styling, React does not rec ...

How to automatically open JQuery Accordion panels when the page loads

My Accordion loads with the 1st panel open upon page load, but I am looking for a way to have the entire Accordion closed by default. Any help or suggestions on how to achieve this would be highly appreciated. Thank you for your assistance. FIDDLE http:// ...

How can I transform an HTML element into a textarea using CSS or JavaScript?

While browsing a webpage, I discovered a <div> element with the class .plainMail and I want to find a way to easily select all its text by simply pressing Ctrl+A. Currently using Firefox 22, I am considering converting the div.plainMail into a texta ...

In Javascript, you can enhance your axes on a graph by adding labels at both the

Is there a way to add labels at the beginning and end of the axes to indicate the importance level, such as "not very important" and "very important"? I am currently utilizing a slider program from here. Since I am new to JavaScript, I would greatly appre ...

enhancing look of external tool

I have a third-party widget with inline CSS that displays a table on my website. Is there a way to strip out the inline CSS from the widget before adding it to my page so that only my custom css file styles are applied? The HTML structure of the widget i ...

Navigation bar's active area does not span the full height

I'm facing some issues with the navigation bar on my responsive website. One issue is that the clickable area for the links does not extend to the full height of the nav bar, and I would like it to cover the entire height. Another problem arises whe ...

Any suggestions on how to secure my socket connection following user authentication in redux?

After onSubmit, userAction.login is called which then dispatches "SUCCESS_AUTHENTICATE" to set the token of the user and socket state in their respective reducers. How can I proceed to trigger socket.emit("authenticate", {token})? ...

Transferring the "key" and "values" data from a JSON object to a perl script

I am currently working on developing a shopping cart application. All the items stored in the shopping cart are kept within a JavaScript object called Cart, with data structured like {"sku"=quantity}. For instance: Cart={"5x123"=1,"5x125"=3} At this ...

Tips for using jQuery to identify the most recently modified row in an HTML table

Is there a way to identify the most recently modified (either newly added or changed) row in an HTML table? ...

Exploring elements within a JavaScript array

I'm struggling to retrieve model objects from my view model. It seems like a JavaScript/KnockoutJS familiarity issue, so any guidance is welcomed. Here is the code snippet: <!-- VIEW --> <select data-bind="options: allTypes, ...

Challenges arise when working with Vue 3.2 using the <script setup> tag in conjunction with TypeScript type

Hey there! I've been working with the Vue 3.2 <script setup> tag along with TypeScript. In a simple scenario, I'm aiming to display a user ID in the template. Technically, my code is functioning correctly as it shows the user ID as expect ...

Tips for initializing the store in Vue when the application first starts

Seeking assistance in loading products from my pinia store upon the initial load of my Vue app. Check out my app.js below: import {createApp} from "vue"; import App from "./App.vue"; import router from "./Router/index"; impor ...

Error Encountered in NextJS - Hydration Unsuccessful

Currently, I am utilizing NextLink in my project to generate links. However, it appears that using NextLink is causing the following error: Hydration failed because the initial UI does not match what was rendered on the server. Upon inspecting the console ...