简单的一批,直接上代码。
<template>
<div>
<button @click="show=!show">button</button>
<transition name="my">//这里用transition标签嵌套需要添加动画效果的元素,name是用在css样式中的名字
<h1 v-if="show">
动画效果
</h1>
</transition>
</div>
</template>
<script>
export default {
data() {
return {
show: true
}
}
}
</script>
<style>
.my-enter,.my-leave-to{//这里直接设置起始状态样式
opacity: 0;
}
.my-enter-active,.my-leave-active{//这里设置过渡样式
transition: all 1s;
}
</style>
你就说简不简单吧?下面这些状态就是唯一的难点。你要用自己的方法记住他的状态。
name-enter 表示 我要从起始点出发了!
和name-leave-to一起记。我要离开了,去起始点。
上两个都表示起始状态,也就是opacity为0时的状态。
再搭配上name-enter-to,enter-leave-to就可以用起来啦。
补充,掌握了基本用法来看看第三方动画css库洛
简单的一批
npm install animate.css --save
main.js中加入
import animated from 'animate.css'
Vue.use(animated)
然后就直接用起来就阔以了啦
<transition enter-active-class="animated zoomOut" leave-active-class="animated bounce">
<h1 v-if="show">
动画效果
</h1>
</transition>
那个zoomOut和bounce只是animate万千样式库中的两个,你可以在这里面选你喜欢的翻牌子。https://daneden.github.io/animate.css/
那个类里面的animated是必须要加上去的啦。不然没有用喔!
动画之三:
使用动画钩子函数实现半场动画,就是说单向动画,比如你收一个东西进购物车,它会变成一个小球跳进你的购物车。但是你删除购物车里的东西,它没必要跳回去吧。动画钩子函数是实现半场动
画最好的方式。双向动画明显是上两个方法要好用的多
<template>
<div>
<button @click="show=!show">
动画
</button>
<transition @before-enter="beforeEnter" @enter="enter" @after-enter="afterEnter">
<h1 v-if="show">巴啦啦小魔仙</h1>
</transition>
</div>
</template>
<script>
export default {
data() {
return {
show: true,
}
},
methods:{
beforeEnter:function (el) {
el.style.transform='translate(0,0)'
},
enter:function (el,done) {
el.offsetWidth
el.style.transform='translate(150px,150px)'
el.style.transition='all 1s'
done()
},
afterEnter:function(el){
this.show=!this.show
}
}
}
</script>
<style>
</style>
last but notleast
如果你要对v-for的子组件使用动画,你就得把transition改成transition-group喔!
animate之究极demo。一个文件懒得传git了。
<template>
<div>
<input v-model="id" placeholder="id"> <input v-model="name" placeholder="name">
<button @click="add">添加</button>
<ul>
<transition-group name="li" appear tag="ul">
<li v-for="item in arrlist" v-bind:key="item.id" @click="remove(item.id)">
{{item.id}}--{{item.name}}
</li>
</transition-group>
</ul>
</div>
</template>
<style scoped>
.li-enter, .li-leave-to {
opacity: 0;
transform: translateX(80px)
}
.li-enter-active, .li-leave-active {
transition: all 1s ease;
}
.li.move {
transition: all 1s ease;
}
li {
text-align: center;
width: 100%;
border: 1px skyblue dashed;
border-radius: 5px;
margin-top: 10px;
}
li:hover {
background-color: lightpink;
}
</style>
<script>
export default {
data() {
return {
id: '',
name: '',
arrlist: [
{
id: '0',
name: '1'
},
{
id: '1',
name: '2'
},
{
id: '2',
name: '3'
},
{
id: '3',
name: '4'
},
{
id: '4',
name: '5'
},
]
}
},
methods: {
add: function () {
this.arrlist.push({id: this.id, name: this.name})
this.id = ''
this.name = ''
},
remove: function (i) {
for(var j=0;j<this.arrlist.length;j++){
if(this.arrlist[j].id==i){
this.arrlist.splice(j,1)
break
}
}
}
}
}
</script>
<style>
</style>