vue实现div变换
Vue 实现 div 变换的方法
动态绑定 class 或 style
通过 v-bind:class 或 v-bind:style 实现样式变换。例如点击按钮切换背景色:
<template>
<div
:class="{ 'active': isActive }"
:style="{ backgroundColor: bgColor }"
@click="toggle"
>
点击我变换样式
</div>
</template>
<script>
export default {
data() {
return {
isActive: false,
bgColor: '#fff'
}
},
methods: {
toggle() {
this.isActive = !this.isActive
this.bgColor = this.isActive ? '#f00' : '#fff'
}
}
}
</script>
<style>
.active {
transform: scale(1.2);
transition: all 0.3s;
}
</style>
使用过渡动画
通过 Vue 的 <transition> 组件实现动画效果:

<template>
<button @click="show = !show">切换</button>
<transition name="fade">
<div v-if="show">会淡入淡出的内容</div>
</transition>
</template>
<script>
export default {
data() {
return { show: true }
}
}
</script>
<style>
.fade-enter-active, .fade-leave-active {
transition: opacity 0.5s;
}
.fade-enter, .fade-leave-to {
opacity: 0;
}
</style>
动态组件切换
使用 <component :is=""> 实现组件级变换:

<template>
<button @click="currentComponent = 'ComponentA'">显示A</button>
<button @click="currentComponent = 'ComponentB'">显示B</button>
<component :is="currentComponent"/>
</template>
<script>
import ComponentA from './ComponentA.vue'
import ComponentB from './ComponentB.vue'
export default {
components: { ComponentA, ComponentB },
data() {
return {
currentComponent: 'ComponentA'
}
}
}
</script>
使用 CSS Grid/Flex 布局变换
通过响应式数据控制布局变化:
<template>
<div class="container" :style="{ gridTemplateColumns: columns }">
<div v-for="n in 3" :key="n">项目{{n}}</div>
</div>
<button @click="toggleLayout">切换布局</button>
</template>
<script>
export default {
data() {
return {
isColumn: true
}
},
computed: {
columns() {
return this.isColumn ? '1fr 1fr 1fr' : '1fr'
}
},
methods: {
toggleLayout() {
this.isColumn = !this.isColumn
}
}
}
</script>
<style>
.container {
display: grid;
gap: 10px;
}
</style>
结合第三方动画库
例如使用 animate.css 实现复杂动画:
<template>
<div
class="box"
@click="animate"
:class="{'animate__animated': shouldAnimate, 'animate__bounce': shouldAnimate}"
>
点击触发动画
</div>
</template>
<script>
export default {
data() {
return {
shouldAnimate: false
}
},
methods: {
animate() {
this.shouldAnimate = true
setTimeout(() => {
this.shouldAnimate = false
}, 1000)
}
}
}
</script>
<style>
@import 'animate.css';
.box {
width: 100px;
height: 100px;
background: #42b983;
}
</style>






