
關鍵詞:動畫封裝——進行可復用
一、如何封裝?
1、使用:局部組件傳遞數據+局部組件中使用JS動畫
2、原理:將動畫效果完全第封裝在一個名為<fade>的組件中,今后如要復用,只需要復制有其組件名的部分,然后修改dom元素標簽名稱。使用任何樣式,只需要從組件中進行相應地修改,無需再在全局中定義CSS動畫。
3、代碼如下:
<!DOCTYPE html>
<html lang="en">
<head><meta charset="UTF-8"><title>Vue中的動畫封裝</title><script src="./vue.js"></script>
</head>
<body><div id="root"><fade :show="show"><div v-show="show">hello world</div></fade> <fade :show="show"><h1 v-show="show">hello world</h1></fade> <button @click="handleClick">點擊</button></div> <script>Vue.component('fade',{props: ['show'],template: `<transition @before-enter="handleBeforeEnter"@enter="handleEnter"><slot v-if="show"></slot></transition>`,methods: {handleBeforeEnter: function(el){el.style.color = 'red'},handleEnter: function(el,done){setTimeout(()=>{el.style.color = 'green'done()},2000)}}})var vm = new Vue({el: "#root",data: {show: false},methods: {handleClick: function(){this.show = !this.show}}})</script></body>
</html>
試一下吧:
