vue中使用vue-lottie动画

Vue 中的动画

vue-lottie 使用 这个类库主要就是加载 JSON 形成动画

(1) 安装

npm install --save vue-lottie

(2) 基础组件必须要有

  • lottie.vue
<template>
  <div :style="style" ref="lavContainer"></div>
</template>

<script>
  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',
        loop: this.options.loop !== false,
        autoplay: this.options.autoplay !== false,
        animationData: this.options.animationData,
        rendererSettings: this.options.rendererSettings
      })
      this.$emit('animCreated', this.anim)
    }
  }
</script>

(3)使用的时候,引用 json 必须要有 default 否则会报错

<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>

<script>
  import Lottie from '@/pages/Common/Lottie'
  // import * as animationData from '@/assets/197-glow-loading.json';
  import * as animationData from '@/assets/data.json'
  export default {
    components: {
      Lottie: Lottie
    },
    data() {
      return {
        defaultOptions: { animationData: animationData.default }, // 必须有default
        animationSpeed: 1
      }
    },
    methods: {
      handleAnimation: function(anim) {
        this.anim = anim
      },
      stop: function() {
        this.anim.stop()
      },
      play: function() {
        this.anim.play()
      },
      pause: function() {
        this.anim.pause()
      },
      onSpeedChange: function() {
        this.anim.setSpeed(this.animationSpeed)
      }
    }
  }
</script>

<style lang="less" scoped></style>

(4) axios 中使用 loading 动画

(i)在 vuex 中写一个状态来控制 loading 组件的显示和隐藏

export const store = new Vuex.Store({
  state: {
    isShow: false
  }
})

(ii) Axios 拦截器配置

axios.interceptors.request.use(function(config) {
  store.state.isShow = true //在请求发出之前进行一些操作
  return config
})
//定义一个响应拦截器
axios.interceptors.response.use(function(config) {
  store.state.isShow = false //在这里对返回的数据进行处理
  return config
})

(iii)在 app.vue 中引入 loading 组件

<loading v-if="this.$store.state.isShow"></loading>

文章作者: 雾烟云
版权声明: 本博客所有文章除特別声明外,均采用 CC BY 4.0 许可协议。转载请注明来源 雾烟云 !
  目录