今天给大家, 介绍一下, 怎样在Vue中实现多元素和多组件的动画。
1、多元素实现的代码
注意: transition-group 标签, 包含多个元素, 使用它,必须对子组件添加key 属性。否则报错。
<head>
<meta charset="UTF-8">
<title> Vue 中夺多个元素 或组件的过渡</title>
<script src = "vue.js"></script>
<style>
.v-enter, .v-leave-to {
opacity : 0;
}
.v-enter-active, .v-leave-active {
transition: opacity 1s;
}
</style>
</head>
<body>
<!-- 必须得 key 值, 要不然会报错 -->
<div id = "myApp">
<transition-group>
<div v-if = "show" key = "hello" >
Good morning, world!
</div>
<div v-else key = "bye">
Good evening, World!
</div>
</transition-group>
<button @click = "handleClick"> Toggle </button>
</div>
<script>
new Vue({
el : "#myApp",
data : {
show : true
},
methods : {
handleClick : function() {
this.show = !this.show
}
}
})
</script>
</body>
2、在组件中实现动画
注: transition 标签
mode 是过渡模式:
in-out : 先进来, 后出去
out-in : 先出去, 后进来;
:is , vue中动态进行换组件,:is = "组件名称"
<head>
<meta charset="UTF-8">
<title> Vue 中夺多个元素 或组件的过渡</title>
<script src = "vue.js"></script>
<style>
.v-enter, .v-leave-to {
opacity : 0;
}
.v-enter-active, .v-leave-active {
transition: opacity 1s;
}
</style>
</head>
<body>
<!-- 必须得 key 值, 要不然会报错 -->
<div id = "myApp">
<transition mode = "out-in">
<component :is="type"></component>
</transition>
<button @click = "handleClick"> Toggle </button>
</div>
<script>
Vue.component('child', {
template : "<div> Child</div>"
});
Vue.component("child-one", {
template : "<div> Child-One </div>"
})
new Vue({
el : "#myApp",
data : {
type : "child"
},
methods : {
handleClick : function() {
this.type = this.type === "child" ? "child-one" : "child"
}
}
})
</script>
</body>
网友评论