指令代码
要实现Vue2的指令,可以按照以下步骤进行:
创建一个指令对象。
export default {inserted: (el, binding) => {// 触发抖动效果if (!binding.value) return el.classList.remove('shake-animation')el.classList.add('shake-animation')const animationEnd = function () {el.removeEventListener('animationend', animationEnd)el.classList.remove('shake-animation')}el.addEventListener('animationend', animationEnd)},update: (el, binding) => {if (!binding.value) return el.classList.remove('shake-animation')el.classList.add('shake-animation')},
}
注册指令。
Vue.directive('shake', shake);
在模板中使用指令。
<div v-shake=""></div>
shake-animation动画
.shake-animation {animation: shake-animation 0.82s infinite cubic-bezier(0.36, 0.07, 0.19, 0.97) both;transform: translate3d(0, 0, 0);backface-visibility: hidden;perspective: 1000px;
}@keyframes shake-animation {10%,90% {transform: translate3d(-1px, -1px, 0);}20%,80% {transform: translate3d(1px, 1px, 0);}30%,50%,70% {transform: translate3d(-1px, -1px, 0);}40%,60% {transform: translate3d(1px, 1px, 0);}
}