我想在 vue.js-application 中創建抖動效果。我找到了一個例子,我可以用它創建一個用 JavaScript 創建的抖動效果,但是在 vue.js 中不能使用 eventListener - 所以我不知道如何在 vue.js 中使用這個代碼。
你知道如何在沒有 eventListener 的情況下在 vue.js 中使用這個影片嗎?
這是我要調整的代碼:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<link rel="stylesheet" href="./main.css">
<title>3d Vector Kata</title>
<style>
/* Standard syntax */
@keyframes shake {
10%, 90% {
transform: translate3d(-1px, 0, 0);
}
20%, 80% {
transform: translate3d(2px, 0, 0);
}
30%, 50%, 70% {
transform: translate3d(-4px, 0, 0);
}
40%, 60% {
transform: translate3d(4px, 0, 0);
}
}
.apply-shake {
animation: shake 0.82s cubic-bezier(.36,.07,.19,.97) both;
}
</style>
</head>
<body>
<form id="test-form">
<input type="text" id="test-input">
<button type="submit" id="submit-button" onclick="shakeAnimation()">Submit</button>
</form>
<script src="./index.js"></script>
</body>
</html>
<script>
const input = document.querySelector("input#test-input");
const submit = document.querySelector("button#submit-button");
submit.addEventListener("click", (e) => {
e.preventDefault();
if(input.value === "") {
submit.classList.add("apply-shake");
}
});
submit.addEventListener("animationend", (e) => {
submit.classList.remove("apply-shake");
});
</script>
uj5u.com熱心網友回復:
在您的示例中,事件偵聽器所做的唯一事情就是切換一個類。
所以你可以使用條件類語法<button :>;
檢查代碼框:https ://codesandbox.io/s/shake-effect-vue-71306745-z912ms?file=/src/App.vue
所以你可以做這樣的事情:
<template>
<div id="app">
<button :class="{ 'apply-shake': shake }" @click="shakeAnimation()">
Shake
</button>
</div>
</template>
<script>
export default {
data() {
return {
shake: false,
};
},
methods: {
shakeAnimation() {
this.shake = true;
setTimeout(() => {
this.shake = false;
}, 820); // timeout value depending on the duration of the animation
},
},
};
</script>
<style>
@keyframes shake {
10%,
90% {
transform: translate3d(-1px, 0, 0);
}
20%,
80% {
transform: translate3d(2px, 0, 0);
}
30%,
50%,
70% {
transform: translate3d(-4px, 0, 0);
}
40%,
60% {
transform: translate3d(4px, 0, 0);
}
}
.apply-shake {
animation: shake 0.82s cubic-bezier(0.36, 0.07, 0.19, 0.97) both;
}
</style>
uj5u.com熱心網友回復:
基于@Zecka 的解決方案,使用事件監聽器而不是超時更好:
https://codesandbox.io/s/shake-effect-vue-71306745-forked-hebrob?file=/src/App.vue:471-754
<script>
export default {
data() {
return {
shake: false,
};
},
mounted() {
this.$refs.submit.addEventListener("animationend", () => {
this.shake = false;
});
},
methods: {
shakeAnimation() {
this.shake = true;
},
},
};
</script>
在 Vue 中使用事件偵聽器不是問題@Florian27,您可以通過添加 ref 屬性或簡單地使用document.querySelector甚至更好地輕松定位組件中的任何元素,this.$el.querySelector以便將其范圍限定到您的組件,然后使用純 JS 附加事件偵聽器。
uj5u.com熱心網友回復:
非常感謝您的快速答復。它作業得很好!
另一個問題:我有不止一個物件。如果我單擊一個物件,所有物件都被搖動,但我只想搖動我剛剛單擊的物件。somoene 也有這個問題的答案嗎?
我的想法是只呼叫一個具有特定 ID 的物件,但在我的示例中每次都不起作用。也許你有更好的想法。
轉載請註明出處,本文鏈接:https://www.uj5u.com/caozuo/435023.html
標籤:javascript html css Vue.js 事件监听器
