要在 Vue 3 中實現點擊按鈕讓圖片旋轉 90 度,你可以使用 CSS 轉換和 Vue 的事件處理來完成。這里是一個基本的示例:
首先,在你的組件的模板中,添加一個按鈕和一個應用轉換的圖像:
<template> | |
<div> | |
<button @click="rotateImage">旋轉圖片</button> | |
<img :class="{ rotated: isRotated }" src="your-image-source.jpg" alt="Image" /> | |
</div> | |
</template> |
在這里,:class="{ rotated: isRotated }"
是一個綁定,它會動態地將rotated
類添加到圖像中,當isRotated
為true
時。
然后,在你的組件的<script setup>
中,定義isRotated
和處理按鈕點擊事件的函數:
<script setup> | |
import { ref } from 'vue'; | |
const isRotated = ref(false); | |
function rotateImage() { | |
isRotated.value = !isRotated.value; | |
} | |
</script> |
在這里,ref
是 Vue 的一個函數,用于創建一個響應式引用。isRotated
是一個響應式引用,當它的值變化時,任何綁定到它的類或屬性都會更新。
最后,在你的組件的 CSS 中,定義rotated
類來應用轉換:
<style> | |
.rotated { | |
transform: rotate(90deg); | |
} | |
</style> |
在這里,transform: rotate(90deg);
將元素旋轉 90 度。
請注意,這個示例中的旋轉是無限循環的。如果你只想旋轉一次,你可以在rotateImage
函數中設置一個額外的狀態變量來跟蹤旋轉次數,并在適當的時候重置isRotated
。