Vue.js Series Tutorial 5: animations

Source: Internet
Author: User

Original: intro-to-vue-5-animations

Translator: Nzbin

Translator's Words: After two weeks of efforts, finally completed the series of translation, due to time factors and personal level is limited, and there is no detailed proofreading, which still have a lot of difficult to understand the place. I and the original author of the same intention, I hope that we can gain through this series of articles, at least can increase the fun of learning, I also on the way of learning, the experience will be shared with YOU.

This is the fifth part of the JavaScript framework Vue.js five Tutorials. In the final part of this series, we will learn to animate (if you know me, you know that this chapter will come sooner or later). This series of tutorials is not a complete user manual, but rather a basic knowledge that gives you a quick overview of Vuejs and its uses.

Series Articles:
    1. rendering, directives, Events
    2. components, Props, Slots
    3. Vue-cli
    4. Vuex
    5. Animation (here You are!)
Background knowledge

Built-in <transition> and <transition-group> components support both CSS and JS hooks. If you are familiar with React, the concept of transition components is not unfamiliar to you, because in the life cycle hook, it is ReactCSSTransitionGroup similar, but there are significant differences, which makes the nerd I am very excited.

Let's talk about CSS transitions before we discuss CSS animations, and then introduce the JS animation hooks and the life cycle approach to animations. The transition state is beyond the scope of this article, but this is Possible. This is a good example of what I have done for This. As long as I can get enough rest, I am sure I will write the Article.

Transitions vs. animations

You may not understand why transitions and animations fall into different parts of this article, let me explain that although they are similar, there are different places. A transition is the insertion of a value from one state to Another. We can do a lot of complicated things, but it's very simple. From the start state, to the end state, and back Again.

Animations are a little different, you can set multiple states in a Declaration. For example, you can set a keyframe in the position of the animation 50%, then set a completely different state in the 70% position, and so On. You can implement very complex motion by setting the delay Property. Animations can also be used for transitions, which only need to be inserted from beginning to end, but transitions cannot insert multiple values like Animations.

In terms of tools, both are Useful. The transition is like a "saw" and animated like a "chainsaw." Sometimes you need to understand that it may be foolish to buy expensive equipment. For large projects, investing in "chainsaw" is more Meaningful.

Having learned this knowledge, we will discuss the vue!

CSS transitions

Suppose there is a simple modal window. Show or hide the modal window by clicking the Button. According to the previous section, we can do this: create a Vue instance of a button, create a subassembly in the instance, set the state of the data, and enable the display and concealment of the subcomponents by toggling the Boolean value and adding event Handling. We can use v-if or v-show switch component Visibility. You can also use the slot to place a toggle button on the modal window.

<div id= "app" >  
Const CHILD = {  template: ' #childarea '};new Vue ({  el: ' #app ',  data () {    return {      isshowing:false    }  },  methods: {    toggleshow () {      this.isshowing =!this.isshowing;    }}  ,  Components: {    Appchild:child  }});

It works, but the modal windows are a bit Discordant.

We have used v-if the load and unload of implementing components, so if we add conditions to the transition component, Vue can track the event changes:

<transition name= "fade" >  <app-child v-if= "isshowing" class= "modal" >    <button @click = " Toggleshow ">      Close    </button>  </app-child></transition>

now, we can use ready-made <transition> components. The transition hook adds v- a prefix that we can use in CSS. Where enter/leave you define where the animation starts the first frame, enter-active/leave-active define the animation run phase--you need to place the animation properties here, enter-to/leave-to Specifying the position of the element on the last Frame.

I'm going to use the instructions in my official website, because I think it's a straightforward description of the class Name:

personally, I don't often use the default v- prefix. I often name transitions so that there is no conflict if I want to apply to another Animation. This is not hard to do, as you can see, we simply add a property to the transition component name : name="fade" .

Now that we have the hooks, we can use them to create transitions:

. fade-enter-active,. fade-leave-active {  transition:opacity 0.25s ease-out;}. fade-enter,. fade-leave-to {  opacity:0;}

.fade-enter-activeand .fade-leave-active classes will be applied to the actual Transition. This is the normal CSS, you can use cubic-beziers in the transition to implement eases, delays, or specify other Properties. In fact, it is equally valid to place the transition properties of these classes in the Component's class as the default Setting. These do not need to be defined by the transition component Hooks. They simply wait for the component to change and then add the change to the transition (so you still need the transition component and. Fade-enter,. fade-leave-to). The reason I use the enter-active and leave-active classes is that I can reuse these transition properties on other elements without having to apply the same CSS on each instance.

Another point to note: I used attributes on every active class ease-out . These properties apply only to Transparent Elements. But if you use transition properties such as transform, you might want to separate the two, apply to the ease-out enter-active class and ease-in apply to the Enter-leave class (or cubic-beziers, which generally behaves the same curve). I found it makes the animation look more ... Elegant (haha).

You also notice that I set The. fade-enter and The. fade-to property to opacity: 0 . This is the initial and end position of the animation, the initial state of the load, and the end state at the time of Uninstallation. You may think .fade-enter-to and .fade-leave should set opacity: 1 . But it is not necessary because it is the default state of the component, so this will be superfluous. CSS transitions and animations if not set, the default state is always Used.

Run very well! But what happens if we want the background content to fade out of view, so that the modal window is centered and the background loses focus? We cannot use <transition> components because the components work based on the parts that are loaded or unloaded, and the background is just around. We can use a state-based transition class to change the background by changing CSS transitions using classes:

<div v-bind:class= "[isshowing? blurclass: ', bkclass]" >    
. BK {  Transition:all 0.1s ease-out;}. Blur {  Filter:blur (2px);  opacity:0.4;}
New Vue ({  el: ' #app ',  data () {    return {      isshowing:false,      bkclass: ' bk ',      blurclass: ' Blur '    }  },  ...});
CSS Animations

Now that We've learned how transitions work, we can create good CSS animations with these core concepts. transitions We still use the <transition> component and give it a name so we can use the class Hooks. The difference between animations and transitions is not just setting the final state or inserting states between the beginning and the end, we'll use the CSS to @keyframes create interesting and cute Effects.

In the previous section, we talked about a special name for the transition component that can be used as a class Hook. But in this section, we'll take a step further and apply different kinds of hooks in different animations. You may recall that all interesting animations are based on enter-active and Leave-active. We can set different properties for each class hook, but we can further give each instance a special Class:

enter-active-class="toasty"
leave-active-class="bounceOut"

This means that we can reuse these classes and even set the classes in the CSS animation library.

For example, we want a ball bouncing in and out:

<div id= "app" >  

For bounce animations, If you use CSS, we need to set up a lot of keyframes (while using JS requires only one line of code), we will use SASS mixin to keep the style concise (without repeating the settings). To get the ball component to start off the screen, we set up a .ballmove-enter class:

@mixin ballb ($yaxis: 0) {  transform:translate3d (0, $yaxis, 0);} @keyframes Bouncein {   1% {@include ballb ( -400px);}  20%, 40%, 60%, 80%, 95%, 99%, 100% {@include ballb ()}  30% {@include ballb ( -80px);}  50% {@include ballb ( -40px);}  70% {@include ballb ( -30px);}  90% {@include ballb ( -15px);}  97% {@include ballb ( -10px);}}. Bouncein {   animation:bouncein 0.8s cubic-bezier (0.25, 0.46, 0.45, 0.94) both;}. Ballmove-enter {  @include ballb ( -400px);}

For the ball roll out animation, We need to create two different animations. This is because the transform will be applied to the entire subassembly, so that the entire component will Rotate. So we use translation to move the component out of the screen, and to add rotation to the ball by rotation:

@keyframes rollout {   0% {transform:translate3d (0, 300px, 0);}  100% {transform:translate3d (1000px, 300px, 0);}} @keyframes ballroll {  0% {transform:rotate (0);}  100% {transform:rotate (1000deg);}}. Rollout {   width:60px;  height:60px;  animation:rollout 2s cubic-bezier (0.55, 0.085, 0.68, 0.53) both;   div {    animation:ballroll 2s cubic-bezier (0.55, 0.085, 0.68, 0.53) both;   }}
Transition mode

Do you remember when I said that Vue provides a useful feature in the transition that makes me a nerd happy? This is a point I like very much. If a component transitions away and you add a transition to another component, you'll see two components at the same time at a strange moment, and then quickly return to their original position (this is an example from the Vue documentation):

Vue provides a transition mode so that when one component transitions out, another component that transitions in does not flicker or block in strange places. The reason for this is the orderly transition rather than the simultaneous occurrence. There are two modes to choose From:

in-out: The new element transitions first, and the current element transitions out after Completion.

out-in: The current element transitions first, and the new element transitions into after Completion.

Take a look at the following Example. You can observe the-mode of the transition component out-in , which appears only when a picture is turned over:

<transition name= "flip" mode= "out-in" >  <slot v-if= "!isshowing" ></slot>  </transition>

If we get rid of this transition pattern, you'll see that part of the flip is blocking the other part, and the animations are somewhat uncoordinated, which is not the effect we want:

JS Animation

There are many easy-to-use JS hooks for our animations. All hooks are passed into the el parameter (the abbreviation of element), except for the animation hooks (enter and leave), which are also passed in done as parameters, as you can guess, it is the function of telling the Vue animation to End. YOU'LL Notice that we've bound the CSS to a value of false, so that the component knows we're going to use JavaScript instead of CSS.

<transition   @before-enter= "beforeenter"  @enter = "enter"  @after-enter= "afterenter"  @ enter-cancelled= "entercancelled"  @before-leave= "beforeleave"  @leave = "Leave"  @after-leave= " Afterleave "  @leave-cancelled=" leavecancelled "  : css=" false ">  </transition>

At the most basic level, this is what you need to start animating and ending animations, including the relevant methods:

<transition   @enter = "enterel"  @leave = "leaveel"  : css= "false" > <!--put element here--> </ Transition>
Methods: {   enterel (el, done) {     //entrance animation do     ();  },  leaveel (el, done) {    //exit Animation done    ();  },}

In the example below, I've plugged in a greensock timeline in the Hooks:

New Vue ({  el: ' #app ',  data () {    return {      message: ' This was a good place to type things. ',      load:fa LSE    }  ,  methods: {    beforeenter (el) {      tweenmax.set (el, {        transformperspective:600,        perspective:300,        transformstyle: "preserve-3d",        autoalpha:1      });    },    Enter (el, done ) {      ...            Tl.add ("drop");      for (var i = 0; i < wordCount; i++) {        tl.from (split.words[i], 1.5, {          z:math.floor (math.random () * (1 + 150- -150) + -150),          ease:Bounce.easeOut        }, "drop+=0." + (i/0.5));       ...          }  }});

Note the two interesting things in the animation above, I pass them as arguments to the Timeline instance, {onComplete:done} and I use beforeEnter hooks to place the TweenMax.set code, which allows me to set arbitrary properties on the word before the animation starts, which is similar transform-style: preserve-3d .

The important point is that you can also set the default state you want for the animation directly in the CSS. Someone asked me how to decide whether to set properties in CSS or in TweenMax.set . Based on experience, I usually set the special properties of some of the animations I need in TweenMax.set . This way, if something in the animation changes and I need to update it, it's already in my workflow.

Life-cycle Hooks in animations

Everything is fine, but what if the animations are complicated and you need to manipulate a lot of DOM elements? Now is the best time to use the life cycle Approach. In the following example, we use <transition> components and mounted() methods to create Animations.

If we add a transition to a single element, we will use the transition component, for example, when the line around the phone button is displayed:

<transition   @before-enter= "beforeenterstroke"  @enter = "enterstroke"  : css= "false"  appear>  <path class= "main-button" d= "m413,272.2c5.1,1.4,7.2,4.7,4.7,7.4s-8.7,3.8-13.8,2.5-7.2-4.7-4.7-7.4s407.9, 270.9,413,272.2z "transform=" Translate (0) "fill=" None "/></transition>
Beforeenterstroke (el) {  el.style.strokeWidth = 0;  El.style.stroke = ' Orange ';},enterstroke (el, done) {  Const TL = new Timelinemax ({    oncomplete:done  });  Tl.to (el, 0.75, {    strokewidth:1,    ease:Circ.easeOut  }, 1);  Tl.to (el, 4, {    strokewidth:0,    opacity:0,    ease:Sine.easeOut  });},

But when a component is first displayed, there are 30 elements and more animations, and it's less efficient to put each one transition in the Component. so, we'll Use the same event that the life cycle hook bindings and transition hooks use in the third part:mounted()

Const TORNADOAREA = {  template: ' #tornadoarea ',  mounted () {let    audio = new audio (' https:// S3-us-west-2.amazonaws.com/s.cdpn.io/28963/tornado.mp3 '),        tl = new Timelinemax ();    Audio.play ();    Tl.add ("tornado");    Tornado timeline begins    tl.staggerfromto (". tornado-group ellipse", 1, {      opacity:0    }, {      opacity:1,      ease:Sine.easeOut    }, 0.15, "tornado");    ...    }};

We can use more efficient methods and create complex Effects. Vue provides an intuitive and flexible API, not just to create a component-only front-end architecture, but also to smooth motion and seamlessly connect the Views.

Summarize

This series of articles is not intended to be a document. While We've talked a lot, there are still a lot of things that aren't covered: routing, mixins, server rendering, and so On. There are so many amazing things that can be used. In-depth study, you can see the detailed official documents, this warehouse has a full list of examples and Resources. There is a book called the Majesty of vue.js, as well as the courses above Egghead.io and Udemy.

Thanks to Robin rendle, Chris coyier, Blake Newman and Evan you for proofreading the various parts of this series. I hope this series will explain why I'm so excited about Vue and help you get started and try something new.

Vue.js Series Tutorial 5: animations

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.