uniapp/微信小程序实现加入购物车点击添加飞到购物车动画

1、预期效果

2、实现思路

每次点击添加按钮时,往该按钮上方添加一个悬浮元素,通过位移动画将元素移到目标位置。

  1. 为每个点击元素设置不同的class,才能通过uni.createSelectorQuery来获取每个元素的节点信息;

  2. 添加一个与点击元素一模一样的动画元素;

  3. 获取点击元素的节点信息将动画元素放置到点击元素上方;

  4. 计算动画元素到目标位置的距离,获得xy坐标执行位移动画;

  5. 等待每个动画元素执行动画完毕后移除该元素。

3、核心代码

TypeScript 复制代码
<template>
  <view>
    <!-- 商品列表 -->
    <view v-for="item in goodsList" :key="item.id">
      <view :class="[`add-cart-${item.id}`]" @click="addToCart(item)">加购</view>
    </view>
    <!-- 动画元素列表 -->
    <view
      v-for="item in anims" :key="item.key"
      style="position: fixed; transition: transform 0.5s linear;"
      :style="{
        top: `${item.top}px`,
        left: `${item.left}px`,
        transform: `translate(${item.x}px, ${item.y}px)`,
      }"
    >
      加购
    </view>
  </view>
</template>

<script setup lang="ts">
import { ref } from 'vue';
import uniqueId from 'lodash-es/uniqueId';

const sys = uni.getSystemInfoSync();
const anims = ref<any[]>([]);
const goodsList = ref([{ id: 1 }, { id: 2 }, { id: 3 }])

function addToCart(item) {
  // 添加动画元素
  const key = uniqueId();
  anims.value.push({
    key,
    id: item.id,
    left: 0,
    top: 0,
    y: 0,
    x: 0,
  });
  // 获取点击元素的节点信息
  uni.createSelectorQuery().select(`.add-cart-${item.id}`)
    .boundingClientRect((e: any) => {
      // 初始化起始位置
      anims.value.some((citem) => {
        if (citem.key === key) {
          citem.top = e.top;
          citem.left = e.left;
          return true;
        }
        return false;
      });
      nextTick(() => {
        // 设置目标位置
        anims.value.some((citem) => {
          if (citem.key === key) {
            citem.y = sys.windowHeight - citem.top - 50;
            citem.x = -sys.windowWidth * 0.30;
            setTimeout(() => { // 等待动画执行完毕移除元素
              anims.value.splice(anims.value.findIndex((v: any) => v.key === key), 1);
            }, 500);
            return true;
          }
          return false;
        });
      });
    }).exec();
}

</script>
相关推荐
写不来代码的草莓熊1 天前
vue前端面试题——记录一次面试当中遇到的题(9)
前端·javascript·vue.js
JinSo1 天前
pnpm monorepo 联调:告别 --global 参数
前端·github·代码规范
程序员码歌1 天前
豆包Seedream4.0深度体验:p图美化与文生图创作
android·前端·后端
urhero1 天前
工作事项管理小工具——HTML版
前端·html·实用工具·工作事项跟踪·任务跟踪小工具·本地小程序
二十雨辰1 天前
eduAi-智能体创意平台
前端·vue.js
golang学习记1 天前
从0死磕全栈之Next.js connection() 函数详解:强制动态渲染的正确姿势(附实战案例)
前端
郝学胜-神的一滴1 天前
Three.js光照技术详解:为3D场景注入灵魂
开发语言·前端·javascript·3d·web3·webgl
m0dw1 天前
vue懒加载
前端·javascript·vue.js·typescript
国家不保护废物1 天前
手写 Vue Router,揭秘路由背后的魔法!🔮
前端·vue.js
菜鸟‍1 天前
【前端学习】仿Deepseek官网AI聊天网站React
前端·学习·react.js