vue 数据大屏项目开发中,需要一个switch开关,element ui有类似的效果,不过和设计图的样式还是有差异的,所以就想着自己写一个,这里面的动画我们用的是gsap补间动画。
实现思路
我们首先通过css实现按钮样式,然后给按钮添加点击事件来改变状态,通过状态的变化来触发动画。
实现代码
<template>
<div class="tab cur" @click="getSelecteds">
<div class="tabInner" ref="tabInner"></div>
</div>
</template>
<script>
import gsap from 'gsap'
export default {
name: "tab",
props: {
selected: {
type: Boolean,
default() {
return true;
}
}
},
watch: {
selected() {
this.getSelected()
},
},
mounted() {
this.getSelected()
},
methods: {
getSelecteds() {
console.log(this.selected)
this.$emit('update:selected', !this.selected)
},
getSelected() {
if (this.selected) {
gsap.to(this.$refs.tabInner, {
duration: 0.5,left: 2, onComplete: () => {
console.log('动画完成')
}
})
} else {
gsap.to(this.$refs.tabInner, {
duration: 0.5, left: 37, onComplete: () => {
console.log('动画完成')
}
})
}
}
},
}
</script>
<style lang="scss" scoped>
.tab {
width: 80PX;
height: 24PX;
background: rgba(#7996C8, 0.3);
border-radius: 12PX;
display: flex;
justify-content: center;
align-items: center;
flex-wrap: nowrap;
flex-direction: row;
align-content: flex-start;
position: relative;
.tabInner {
width: 40PX;
height: 20PX;
background: linear-gradient(90deg, #2F76DE 0%, #82A0D5 100%);
border-radius: 10PX;
position: absolute;
left: 2PX;
}
}
.cur {
cursor: pointer;
}
</style>