This is the 27th day of my participation in the August More Text Challenge

A, the premise

If part of the effect is applied more often in the page, you can encapsulate the animation to make the code reusable for future calls.

Second, the steps

  1. Start by creating a basic animation, a simple explicit/implicit toggle animation, as shown below:
<button type="button" @click="handleClick"> </button> <transition> <div v-if="show"> </div> </transition> var vm = new Vue({ el: '#app', data: function() { return { show: true } }, methods: { handleClick: function() { this.show = ! this.show } } })Copy the code
  1. Encapsulate animation components: Write the content to be encapsulated as components and useslotSlot over component content, usedpropsPass the value, you can achieve animation encapsulation. The specific code is as follows:
<style> .v-enter, .v-leave-to { opacity: 0; } .v-enter-active, .v-leave-active { transition: opacity 1s; } </style> <child :show="show"> <div> Vue.component('child', {props: ['show'], template: ` <transition> <slot v-if="show"></slot> </transition>` })Copy the code

The above animation uses CSS, if you want to encapsulate the style as well how to achieve? This is where THE JS animation comes in.

Vue.component('child', {
    props: ['show'],
    template: `
    <transition @before-enter="handleBeforeEnter" @enter="handleEnter" >
    <slot v-if="show"></slot>
    </transition>`,
    methods:{
            handleBeforeEnter(el) {
                    el.style.color = '#000'
            },
            handleEnter(el, done) {
                    setTimeout(() => {
                            el.style.color = 'red';
                            done
                    },1000)
            }
    }
})
Copy the code

The above code uses the javascript hook animation before-enter, enter, after-enter, in this way, all the animation is written in the component, the external only need to call the child component, also do not need to write some global style. This kind of animation encapsulation is recommended because it can encapsulate all animation implementation completely in one component.

Three, use,

The animation effect is completely encapsulated in a component named, and if you want to reuse it, you just copy the part with the component name and modify the content of the DOM element.

<child :show="show"> <div> <child >Copy the code

Four,

Animation encapsulation is intended for reuse.

Use: local component passing data + local component using JS animation.

The idea is to encapsulate reusable animation effects in a custom component that, when needed, simply copies the part with its component name and then modifies the DOM element label name. Using any style, you only need to modify it accordingly from the component, and you no longer need to define CSS animations globally.