• Vue如何通过class或者style实现动画和过渡效果
  • 发布于 2个月前
  • 353 热度
    0 评论
  • 李明发
  • 19 粉丝 36 篇博客
  •   
过渡和动画的区别
过渡: 从一个状态缓慢过渡到另外一个状态,如:背景色由红色缓慢过渡到绿色
动画:一个元素运动的情况,如:从上到下或者从左到右的运动
借助基础的css去实现过渡和动画
一.通过class实现
实现动画效果
通过在标签上添加动态属性:class的方式动态的给元素添加样式类名来实现动画效果
<!-- 堆代码 duidaima.com --> 
@keyframes leftToRight {
    0% {
        transform: translateX(-100px);
    }
    50% {
        transform: translateX(-50px);
    }
    100% {
        transform: translateX(0px);
    }
}
  .animation{
    animation: leftToRight 2s linear;
}


const app = Vue.createApp({
    data() {
        return {
           animate: {
            animation: false
           }
        }
    },
    methods:{
        handleClick() {
            this.animate.animation = !this.animate.animation
        }
    },
    template: `
    <div>
        <div :class="animate">hello world</div>
        <button @click="handleClick">切换</button>
    </div>
    `
})
const vm = app.mount('#root')
上面的例子是通过事件div标签动态的添加和删除样式.animation,从而达到动画效果
实现过渡效果
eg: 一旦背景色发生变化,那么就会在3秒内缓慢的变化背景色
.transition{
      transition: 3s background-color ease;
  }
.blue{
    background: blue;
}
.green{
    background: green;
}


onst app = Vue.createApp({
    data() {
        return {
           animate: {
            transition: true,
            blue: true,
            green: false
           }
        }
    },
    methods:{
        handleClick() {
            this.animate.blue = !this.animate.blue
            this.animate.green = !this.animate.green
        }
    },
    template: `
    <div>
        <div :class="animate">hello world</div>
        <button @click="handleClick">切换</button>
    </div>
    `
})

const vm = app.mount('#root')
上图是默认给div添加.transition样式,然后通过事件让div在.blue样式和.green样式之间切换,从而达到背景色过渡的动画
二.通过style实现
通过style样式,结合事件,修改样式属性的值从而达到过渡的效果
const app = Vue.createApp({
    data() {
        return {
            styleObj: {
                background: 'blue'
            }
        }
    },
    methods: {
        handleClick() {
            if (this.styleObj.background === 'blue') {
                this.styleObj.background = 'green'
            } else {
                this.styleObj.background = 'blue'
            }
        }
    },
    template: `
    <div>
        <div class="transition" :style="styleObj">hello world</div>
        <button @click="handleClick">切换</button>
    </div>
    `
})

const vm = app.mount('#root')
总结
不管是通过class还是通过style,基本上和原生JS差不多,只不过控制style的属性值和class的类名,不再是手动的操作DOM,而是通过控制数据达到更新DOM。

用户评论