vue之加入购物车小球动画

龙承颜
2023-12-01

在做vue小球动画的时候,遇到以下问题,简单的整理以下:

1.问:重绘和重排问题,如:let rf = el.offsetHeight。

   答:  手动获取这个值,会触发浏览器重绘。

2.问:为什么要准备5个小球,如balls:[]。

   答:主要是防止过快出现bug。

3.问:js代码中ball.show设置为false。

   答:主要用于修改dom元素的v-show的值

 

代码如下:

template部分代码:

<div class="ball-container">
<transition-group name="drop"
                    v-on:before-enter="beforeEnter"
                    v-on:enter="enter"
                    v-on:after-enter="afterEnter">
    <div v-for="ball in balls" v-show="ball.show" class="ball" key="a">
    <div class="inner inner-hook" key="b"></div>
    </div>
</transition-group>
</div>

js部分代码:

data() {
  return {
  //每页最多显示5个加按钮,所以在balls中定义5个小球,用于获取5个加按钮,防止过快出现bug
  balls: [
      {show: false},
      {show: false},
      {show: false},
      {show: false},
      {show: false},
  ],
  // 保存下落的小球
  dropBalls: []
  };
},
methods: {
  drop(el) {
    for (let i = 0; i < this.balls.length; i++) {
      let ball = this.balls[i];
      if (!ball.show) {
        ball.show = true;
        ball.el = el;
        this.dropBalls.push(ball);
        return; //结束循环和函数,不会让循环再往后执行了
      }
    }
  },
  beforeEnter(el) {
    //el元素表示小球的div,ball.el表示加按钮
    let count = this.balls.length;
    while (count--) {
      let ball = this.balls[count];
      if (ball.show) {
        let rect = ball.el.getBoundingClientRect();
        let x = rect.left - 32;
        let y = -(window.innerHeight - rect.top - 22);
        el.style.display = '';
        el.style.webkitTransform = `translate3d(0,${y}px,0)`;
        el.style.transform = `translate3d(0,${y}px,0)`;
        let inner = el.getElementsByClassName('inner-hook')[0];
        inner.style.webkitTransform = `translate3d(${x}px,0,0)`;
        inner.style.transform = `translate3d(${x}px,0,0)`;
      }
    }
  },
  enter(el) {
    /* eslint-disable no-unused-vars */
    let rf = el.offsetHeight;//手动获取这个值,触发浏览器重绘
    this.$nextTick(() => {
      el.style.webkitTransform = 'translate3d(0,0,0)';
      el.style.transform = 'translate3d(0,0,0)';
      let inner = el.getElementsByClassName('inner-hook')[0];
      inner.style.webkitTransform = 'translate3d(0,0,0)';
      inner.style.transform = 'translate3d(0,0,0)';
    });
  },
  afterEnter(el) {
    let ball = this.dropBalls.shift();
    if (ball) {
      ball.show = false;// 用于修改dom元素的v-show的值
      el.style.display = 'none';
    }
  }
}

参考:https://www.cnblogs.com/chun321/p/9454987.html

https://github.com/RegToss/Vue-SPA/blob/master/src/components/shopcart/shopcart.vue

 类似资料: