Skip to content

lottie

下载 npm install --save vue-lottie

封装
html
<template>
    <div :style="style" ref="lavContainer"></div>
</template>
js
import lottie from 'lottie-web';
  export default {
    props: {
      options: {
        type: Object,
        required: true
      },
      height: Number,
      width: Number,
    },
    data () {
      return {
        style: {
          width: this.width ? `${this.width}px` : '100%',
          height: this.height ? `${this.height}px` : '100%',
          overflow: 'hidden',
          margin: '0 auto'
        }
      }
    },
    mounted () {
      this.anim = lottie.loadAnimation({
          container: this.$refs.lavContainer,//渲染动画所需容器	
          renderer: 'svg',//渲染类型 svg/canvas/html
          loop: this.options.loop !== false,//是否循环播放
          autoplay: this.options.autoplay !== false,//是否自动播放
          animationData: this.options.animationData,//JSON动画数据
          rendererSettings: this.options.rendererSettings
        }
      );
      this.$emit('animCreated', this.anim)
    }
  }

使用

html
<template>
    <div>
        <lottie :options="defaultOptions" :height="400" :width="400" v-on:animCreated="handleAnimation"/>
        <div>
            <p>Speed: x{{animationSpeed}}</p>
            <input type="range" value="1" min="0" max="3" step="0.5"
                   v-on:change="onSpeedChange" v-model="animationSpeed">
        </div>
        <button v-on:click="stop">stop</button>
        <button v-on:click="pause">pause</button>
        <button v-on:click="play">play</button>
    </div>
</template>
js
import Lottie from './lottie.vue';
import * as animationData from './assets/pinjump.json';
import animationData from './assets/pinjump.json';
export default {
    components: {
      'lottie': Lottie
    },
    data() {
      return {
        defaultOptions: {animationData: animationData},
        animationSpeed: 1
      }
    },
    methods: {
      handleAnimation: function (anim) {
        this.anim = anim;
      },
      stop: function () {//停止动画
        this.anim.stop();
      },
      play: function () {//开始动画
        this.anim.play();
      },
      pause: function () {//暂停动画
        this.anim.pause();
      },
      destroy: function(){
        this.anim.destroy;//销毁动画  
      },
      onSpeedChange: function () {//动画倍速
        this.anim.setSpeed(this.animationSpeed);
      }
    }
  }