// Tutorial //

Super-Easy Property Tweening in Vue.js

Published on November 20, 2017
Default avatar
By Joshua Bemenderfer
Developer and author at DigitalOcean.
Super-Easy Property Tweening in Vue.js

So if you’ve read our previous article on tweening properites in Vue.js, you probably noticed that, well, there’s a lot of code in there. It’s not a super simple thing to rip out and scatter throughout your own projects. So what if there was a way to abstract it so you’d hardly have to write any more code than with CSS transitions? Well, Luke Chinworth was thinking the same thing, and came up with vue-mixin-tween. It uses tween.js and distills the complicated tweening code into a simple mixin which can be included in any component.

Installation

# Yarn
$ yarn vue-mixin-tween
# NPM
$ npm install vue-mixin-tween --save

Usage

Go ahead and throw it right into any old component with a numeric property somewhere. The mixin will create a new reactive property based on the property name you passed in. For example: myProp becomes myPropTween and will update whenever myProp updates.

<template>
  <div>
    <button @click="addAlligators">Add Some Alligators</button>
    <h2>Number of Alligators: {{ numberOfAlligators }}</h2>
    <!-- You may want to Math.floor() the value first as it is a float. -->
    <h2>Number of Alligators: (Tweened) {{ numberOfAlligatorsTween }}</h2>
  </div>
</template>

<script>
import VueMixinTween from 'vue-mixin-tween';

export default {
  data() {
    return {
      numberOfAlligators: 0
    }
  },

  mixins: [
    // The only required argument is the name of the property to tween.
    // The default duration is 500 milliseconds.
    // The default timing function is TWEEN.Easing.Quadratic.Out
    // We're using a "custom" linear timing function here.
    VueMixinTween('numberOfAlligators', 5000, (pos) => pos)
  ],

  methods: {
    addAlligators() {
      this.numberOfAlligators = 500;
    }
  }
}
</script>

And there you have it. It’s dead-simple to customize the duration or even the timing function with far less code-per-component than doing it manually. Awesome!


Want to learn more? Join the DigitalOcean Community!

Join our DigitalOcean community of over a million developers for free! Get help and share knowledge in our Questions & Answers section, find tutorials and tools that will help you grow as a developer and scale your project or business, and subscribe to topics of interest.

Sign up
About the authors
Default avatar
Developer and author at DigitalOcean.

Still looking for an answer?

Was this helpful?
Leave a comment