官方文档
过渡transition:从一个状态到另一个状态
动画animation:元素的运动
CSS实现过渡和动画
在vue中,可以通过基本的CSS实现过渡和动画
<style>
.color-transition {
transition: background-color 1s ease;
}
</style>
<script>
const app = Vue.createApp({
data(){
return {
styleObj: {
background: 'green'
}
}
},
methods:{
handleClick(){
if(this.styleObj.background === 'green'){
this.styleObj.background = 'blue'
}else{
this.styleObj.background = 'green'
}
}
},
template: `
<div class="color-transition" :style="styleObj" @click="handleClick">hello world</div>
`
})
</script>
进入/离开过渡
官方文档
使用transiton封装组件
<div id="demo">
<button @click="show = !show">
Toggle
</button>
<transition name="fade">
<p v-if="show">hello</p>
</transition>
</div>
const Demo = {
data() {
return {
show: true
}
}
}
Vue.createApp(Demo).mount('#demo')
.fade-enter-active,
.fade-leave-active {
transition: opacity 0.5s ease;
}
.fade-enter-from,
.fade-leave-to {
opacity: 0;
}
过渡类名可以自定义,参考官方文档
组件/元素切换动画
<style>
.v-enter-from,.v-leave-to {
opacity: 0;
}
.v-enter-to,.v-leave-from {
opacity: 1;
}
.v-enter-active,.v-leave-active {
transition: all 1s ease-in;
}
</style>
<script>
const app = Vue.createApp({
data(){
return {
show: true
}
},
methods:{
handleClick(){
this.show = !this.show
}
},
template: `
<transition mode="out-in" appear>
<div v-if="show">hello</div>
<div v-else>world</div>
</transition>
<button @click="handleClick">切换</button>
`
})
app.mount("#root")
</script>
vue的切换默认是同时发生的,mode设置为out-in或in-out控制切换顺序,appear让元素第一次出现时有动画
组件的切换可以用composition动态组件实现
列表过渡
<style>
span {
display: inline-block;
padding: 0 10px;
}
.v-enter-from {
opacity: 0;
transform: translateY(20px);
}
.v-enter-to {
opacity: 1;
}
.v-enter-active {
transition: all 1s ease-in;
}
.v-move {
transition: all 1s ease-in;
}
</style>
<script>
const app = Vue.createApp({
data(){
return {
list: [1,2,3]
}
},
methods:{
handleClick(){
this.list.unshift(this.list.length + 1)
}
},
template: `
<transition-group>
<span v-for="item in list" :key="item"> {{item}} </span>
</transition-group>
<button @click="handleClick">增加</button>
`
})
app.mount("#root")
</script>
- 使用transiton-group标签给列表添加过渡
- .v-mode给挪动位置的元素添加过渡样式
状态过渡
文档
当数字从1增加到10时,显示中间变化的过程<script>
const app = Vue.createApp({
data(){
return {
number: 1,
animateNumber: 1
}
},
methods:{
handleClick(){
this.number = 10
if (this.animateNumber < this.number) {
const animation = setInterval(()=>{
this.animateNumber += 1;
if (this.animateNumber === 10){
clearInterval(animation)
}
},100)
}
}
},
template: `
<div>{{animateNumber}}</div>
<button @click="handleClick">增加</button>
`
})
app.mount("#root")
</script>