Vue-购物车系(“移动端” 例:左侧商品选项栏与右侧列表相互响应)【跟据scrollTop,offsetTop,clientHeight,基本结合使用】

Vue中使用ref调用元素减少DOM消耗

在Vue中,我们不用获取dom节点,元素绑定ref之后,直接通过this.$refs即可调用,这样可以减少获取dom节点的消耗。

<ul class="zuo">
          <li v-for="(i,index) in list" :key="i.id" @click="gun(index)"  :class='c==index?"li":"li1"' >
            <!-- 此处判断最后赋的c值是否跟此条数据的index相等,等则高亮渲染 -->
            
            <span>
              {{i.name}}
            </span>
           
          </li>
        </ul>
      <ul class="you" ref="quyu" @scroll="hua()">
        <li v-for="(a,index) in list" :key="a.id" >
          <div class="lei-" ref="name" >{{a.name}}</div>
          <div class="you-kuang" ref="shop">
            <div v-for="b in a.foods" :key="b.id" class="lei-q" @click="dian(b)">
              <div class="lei-q0">
                <img :src='b.icon'/>
              </div>
              <div class="lei-q1">
                <div class="lei-q1zi">{{b.name}}</div>
                <div class="lei-q1zi1">{{b.description}}</div>
                <div class="lei-q1zi1">月售{{b.sellCount}}份  ,  评价{{b.rating}}</div>
                <div class="lei-q1zi2">
                  <span class="lei-q1zi2-1">¥{{b.price}}</span>
                  <span class="lei-q1zi2-2" v-if="b.oldPrice">¥{{b.oldPrice}}</span>
                </div>
              </div>
              <div class="lei-q2">
                  <!-- <span class="lei-q2x1" @click.stop="jian(b,-1)" >-</span> -->
                  <svg xmlns="http://www.w3.org/2000/svg"  xmlns:xlink="http://www.w3.org/1999/xlink" version="1.1" width="0.8rem"
                    height="0.8rem" viewBox="0 0 768 768" class="lei-q2x1" fill="rgb(0,160,220)" @click.stop="jia(b, 1)">
                    <path
                      d="M544.5 415.5v-63h-129v-129h-63v129h-129v63h129v129h63v-129h129zM384 64.5q132 0 225.75 93.75t93.75 225.75-93.75 225.75-225.75 93.75-225.75-93.75-93.75-225.75 93.75-225.75 225.75-93.75z" />
                  </svg>
                  <span class='hua' v-if="ddd">+++</span>
                  <span v-if="b.num>0?true:false">{{b.num}}</span>
                  <!-- <span class="" @click.stop="jia(b,1)">+</span> -->
                  <svg xmlns="http://www.w3.org/2000/svg" v-if="b.num>0?true:false" xmlns:xlink="http://www.w3.org/1999/xlink" version="1.1" width="0.8rem"
                    height="0.8rem" viewBox="0 0 768 768" class="lei-q2x1" fill="rgb(0,160,220)" @click.stop="jian(b, -1)" >
                    <path
                      d="M384 640.5q105 0 180.75-75.75t75.75-180.75-75.75-180.75-180.75-75.75-180.75 75.75-75.75 180.75 75.75 180.75 180.75 75.75zM384 64.5q132 0 225.75 93.75t93.75 225.75-93.75 225.75-225.75 93.75-225.75-93.75-93.75-225.75 93.75-225.75 225.75-93.75zM223.5 352.5h321v63h-321v-63z" />
                  </svg>
              </div>
              <div>

              </div>
          </div>
          </div>
          
        </li>
      </ul>

如上代码为布局代码,可参照 ref 位置。封面有标注

//scrollTop等于是当前ref位置超过外层元素框的值,offsetTop内层元素距外层元素头部的距离

 //clientHeight仅仅包含内边距+高度

 gun(index) {
        this.$refs.name.forEach((v,c) => { //(依据,每个循环里的li里都有一个name)
          // console.log(v)
          if (c == index) {   //通过c值和点击传过来的下标判断
            //scrollTop等于是当前ref位置超过外层元素框的值,offsetTop内层元素距外层元素头部的距离
            this.$refs.quyu.scrollTop = v.offsetTop - 0 
            //此时的v.offserTop值就等于对应name距离外部元素顶的距离,此值为超出外部元素的值,赋给外部元素,让里的距离超出对应的值
            this.konggun = c
            //konggun=c值   给每个区域都给定义一个c值
            console.log(v.offsetTop)
            console.log(this.$refs.quyu.scrollTop)
          }
        })
        this.dong = false
        this.c=index
        // console.log(this.c)
        
      },
      hua(){
        console.log(this.$refs.name[this.konggun].offsetTop)
        Math.floor(this.$refs.quyu.scrollTop) == this.$refs.name[this.konggun].offsetTop - 0 ?this.dong=true:''
        //!!!   -0  可跟据页面调动

        //判断此时超过顶部位置的距离,是否等于,这个ref(name)到顶部的距离。若等于则dong定义为true
          if(this.dong){ //进行判断
            
            this.$refs.name.forEach((v,k)=>{
              let biao=Math.ceil(this.$refs.quyu.scrollTop)//向上取整此时超过顶部的距离
              let min=this.$refs.name[k].offsetTop-0//获取ref(name)到顶部的距离
              // console.log(min)
              //clientHeight仅仅包含内边距+高度
              let max = this.$refs.name[k].offsetTop - 0 + this.$refs.shop[k].clientHeight 
              //获取到当前ref(name)的值到顶部 和 ref(shop)的内边距和高度 的总和 !!!来断定一片区域
              if(biao>=min&&biao<=max){ //判断滑动超出的距离,跟头部和总高的尾部来计算。若在此范围,将k(所在区域的下标值)给到c
                this.c=k
              }
            })
          }
          console.log(this.c)
        }

若有疑问,欢迎在评论区提出ヾノ≧∀≦)o

<template> <div class="container"> <!-- 左侧Tab导航 --> <div class="tabs"> <div v-if="sections.length > 0" class="tabs-wrapper"> <div v-for="(section, index) in sections" :key="index" :class="['tab', { active: activeIndex === index }]" @click="scrollToSection(index)"> <div>{{ section.name }}</div> </div> </div> <div v-else class="empty-container"> <a-empty description="暂无分类" /> </div> </div> <!-- 右侧内容区域 --> <div class="content"> <!-- 粘性定位的表单 --> <a-form :model="searchForm" label-align="left" auto-label-width layout="inline" :size="'large'" class="search-header" ref="searchHeaderRef"> <a-form-item style="width: 320px;" field="base_title" label="能力名称:" size="large"> <a-input allow-clear v-model="searchForm.base_title" placeholder="搜索能力..." @press-enter="fetchTableData" @clear="resetSearch"> <template #prefix> <icon-search /> </template> </a-input> </a-form-item> <a-form-item> <a-space size='large'> <a-button type="primary" size="medium" @click="fetchTableData"> <template #icon><icon-search /></template>查询 </a-button> <a-button type="outline" size="medium" @click="resetSearch"> <template #icon><icon-refresh /></template>重置 </a-button> </a-space> </a-form-item> </a-form> <!-- 加载状态 --> <a-spin :loading="loading" style="width: 100%"> <!-- 使用锚点的章节 --> <div v-if="sections.length > 0" class="section-container" ref="sectionContainerRef" @scroll="handleScroll"> <div v-for="(section, index) in sections" :key="index" :id="section.id" class="section" :ref="setSectionRef"> <!-- 一级分类标题 --> <div class="section-title"> <icon-apps /> {{ section.name }} </div> <!-- 二级分类循环 --> <template v-for="(subSection, subIndex) in section.children" :key="subIndex"> <!-- 二级分类标题 --> <div class="title">{{ subSection.name }}</div> <!-- 三级分类内容 --> <div class="sub-content"> <div v-for="(item, itemIndex) in subSection.children" :key="itemIndex" class="content-item" @click="sceneDetail(item)"> <!-- 背景图片层 --> <div class="img-wrapper"> <img :src="item.image" alt="能力背景" /> </div> <!-- 内容卡片 --> <div class="item"> <div class="item-image"> <img v-if="item.image" :src="item.image" alt="能力图标" /> <div v-else class="image-placeholder"> <a-image width="100" height="100" src="some-error.png" /> </div> </div> <div class="item-text"> <div class="item-title">{{ item.title }}</div> <div class="item-desc">{{ item.description }}</div> </div> </div> </div> </div> </template> </div> </div> <div v-else class="empty-container"> <a-empty description="暂无能力数据" /> </div> </a-spin> </div> </div> </template> <script setup lang="ts"> import { ref, onMounted, nextTick, reactive } from 'vue'; import { IconSearch, IconApps, IconRefresh } from '@arco-design/web-vue/es/icon'; import { Message } from '@arco-design/web-vue'; import { useAbilityMallStore } from '@/store/modules/ability-mall'; import { storeToRefs } from 'pinia'; import { useRouter } from 'vue-router'; import { getAbilityMallList, getabilityMallDetails, createAbilityMall, } from '@/api/abilityMall'; const abilityMallStore = useAbilityMallStore(); const { abilityMallList, abilityMallDetails } = storeToRefs(abilityMallStore); const { getabilityMallDetailsStore } = abilityMallStore; const router = useRouter(); // 定义三级分类数据结构 interface CategoryItem { id: string; title: string; description: string; image: string; } interface SubCategory { id: string; name: string; children: CategoryItem[]; } interface MainCategory { id: string; name: string; children: SubCategory[]; } // 状态管理 const sections = ref<MainCategory[]>([]); const sectionContainerRef = ref<HTMLElement | null>(null); const searchHeaderRef = ref<HTMLElement | null>(null); // 添加搜索表单引用 const sectionRefs = ref<HTMLElement[]>([]); const activeIndex = ref(0); const loading = ref(false); const headerHeight = ref(0); const searchForm = reactive({ base_title: '', }); // 更高效的数据转换函数 const transformData = (apiData: any[]): MainCategory[] => { const categoryMap = new Map<string, MainCategory>(); const subcategoryMap = new Map<string, SubCategory>(); apiData.forEach((item) => { const categoryName = item.base_category; const categoryId = categoryName.replace(/\s+/g, '-').toLowerCase(); // 处理一级分类 if (!categoryMap.has(categoryId)) { categoryMap.set(categoryId, { id: categoryId, name: categoryName, children: [], }); } const category = categoryMap.get(categoryId)!; // 处理二级分类 const subcategoryName = item.base_subcategory; const subcategoryId = `${categoryId}-${subcategoryName .replace(/\s+/g, '-') .toLowerCase()}`; if (!subcategoryMap.has(subcategoryId)) { const subcategory: SubCategory = { id: subcategoryId, name: subcategoryName, children: [], }; subcategoryMap.set(subcategoryId, subcategory); category.children.push(subcategory); } const subcategory = subcategoryMap.get(subcategoryId)!; // 添加三级分类项 subcategory.children.push({ id: item.id, title: item.base_title, description: item.base_content, image: item.base_image, // 添加图片字段 }); }); return Array.from(categoryMap.values()); }; // 设置章节引用 const setSectionRef = (el: any) => { if (el) { sectionRefs.value.push(el); } }; // 获取搜索表单高度 const getSearchHeaderHeight = (): number => { return searchHeaderRef.value?.offsetHeight || 80; }; // 滚动到指定章节 - 修复滚动位置计算 const scrollToSection = (index: number) => { if (!sectionContainerRef.value || index < 0 || index >= sectionRefs.value.length) return; activeIndex.value = index; const targetSection = sectionRefs.value[index]; const headerHeight = getSearchHeaderHeight(); // 精确计算滚动位置:目标位置 - 顶部间距 + 容器滚动位置 const targetOffset = targetSection.offsetTop - headerHeight; sectionContainerRef.value.scrollTo({ top: targetOffset, behavior: 'smooth', }); }; // 初始化滚动监听 const initScrollListener = () => { if (!sectionContainerRef.value) return; // 初始计算一次搜索表单高度 headerHeight.value = getSearchHeaderHeight(); }; // 处理滚动事件 - 修复滚动位置判断逻辑 const handleScroll = () => { if (!sectionContainerRef.value || sectionRefs.value.length === 0) return; const scrollTop = sectionContainerRef.value.scrollTop; const containerHeight = sectionContainerRef.value.clientHeight; const headerHeight = getSearchHeaderHeight(); // 计算有效滚动位置(考虑搜索表单高度) const effectiveScrollTop = scrollTop + headerHeight; // 1. 处理滚动到底部的情况 if (scrollTop + containerHeight >= sectionContainerRef.value.scrollHeight - 10) { activeIndex.value = sectionRefs.value.length - 1; return; } // 2. 精确计算当前激活的section let currentIndex = 0; let closestDistance = Number.MAX_VALUE; // 找到距离顶部最近的section for (let i = 0; i < sectionRefs.value.length; i++) { const section = sectionRefs.value[i]; const distance = Math.abs(section.offsetTop - effectiveScrollTop); if (distance < closestDistance) { closestDistance = distance; currentIndex = i; } } // 3. 处理最后两个section的特殊情况 if (sectionRefs.value.length > 1) { const lastSection = sectionRefs.value[sectionRefs.value.length - 1]; const secondLastSection = sectionRefs.value[sectionRefs.value.length - 2]; // 当滚动位置接近最后两个section时 if (effectiveScrollTop >= secondLastSection.offsetTop - 50) { // 如果已经滚动到最后一个section if (effectiveScrollTop >= lastSection.offsetTop - headerHeight) { currentIndex = sectionRefs.value.length - 1; } else { currentIndex = sectionRefs.value.length - 2; } } } // 只有当索引变化时才更新 if (activeIndex.value !== currentIndex) { activeIndex.value = currentIndex; } }; // 重置搜索 const resetSearch = () => { searchForm.base_title = ''; fetchTableData(); }; // 获取数据 async function fetchTableData() { loading.value = true; try { const { data } = await getAbilityMallList(searchForm); const fakeData = data.filter((item) => item.deleted === 0); sections.value = transformData(fakeData || []); // 重置引用 nextTick(() => { sectionRefs.value = []; // 初始化滚动监听 setTimeout(() => { initScrollListener(); handleScroll(); // 初始计算一次激活状态 // 添加初始滚动位置修正 if (sections.value.length > 0) { scrollToSection(0); } }, 100); }); } catch (error) { console.error('获取能力模型失败:', error); Message.error('获取能力模型失败'); } finally { loading.value = false; } } // 跳转详情 const sceneDetail = async (item: CategoryItem) => { loading.value = true; await getabilityMallDetailsStore(item.id); router.push({ name: 'AbilityDetails', query: { id: item.id }, }); loading.value = false; }; // 生命周期钩子 onMounted(() => { fetchTableData(); }); </script> <style scoped> .container { display: flex; height: 100vh; position: relative; padding: 0; background: #fff; font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, Oxygen, Ubuntu, Cantarell, 'Open Sans', 'Helvetica Neue', sans-serif; } /* 左侧导航样式 */ .tabs { width: 200px; padding: 20px 0; flex-shrink: 0; position: sticky; top: 0; max-height: 100vh; overflow-y: auto; z-index: 10; background: #f9fafb; border-right: 1px solid #e5e6eb; .tabs-wrapper { padding: 0 10px; } .tab { height: 44px; line-height: 44px; text-align: center; margin: 8px 0; font-size: 15px; color: #1d2129; cursor: pointer; position: relative; transition: all 0.3s ease; border-radius: 6px; overflow: hidden; font-weight: 500; &:hover { background: #f2f3f5; color: #3261CE; transform: translateX(3px); } } .tab.active { color: #3261CE; background: #e8f3ff; font-weight: 600; box-shadow: 0 1px 4px rgba(22, 93, 255, 0.15); &::before { content: ''; position: absolute; left: 0; top: 0; height: 100%; width: 3px; background: #3261CE; } } .empty-container { padding: 40px 20px; } } /* 右侧内容区域 */ .content { flex: 1; height: 100%; position: relative; padding: 0; overflow: hidden; display: flex; flex-direction: column; } /* 搜索头部样式 */ .search-header { width: 100%; display: flex; gap: 16px; padding: 15px 24px; background: #fff; border-bottom: 1px solid #e5e6eb; box-shadow: 0 2px 10px rgba(0, 0, 0, 0.03); position: sticky; top: 0; z-index: 20; .header-title { font-size: 20px; font-weight: 600; margin-right: 20px; color: #1d2129; } } /* 分类区域样式 - 关键修改 */ .section-container { flex: 1; overflow-y: auto; scroll-behavior: smooth; padding: 0 24px; position: relative; height: calc(100vh - 80px); /* 减去搜索高度 */ } .section { padding: 32px 0; border-bottom: 1px solid #e5e6eb; &:first-child { padding-top: 24px; } &:last-child { border-bottom: none; } } .section-title { font-size: 22px; color: #1d2129; padding-bottom: 16px; margin-bottom: 16px; border-bottom: 1px solid #e5e6eb; font-weight: 600; display: flex; align-items: center; .arco-icon { margin-right: 10px; color: #3261CE; font-size: 20px; } } .title { font-size: 18px; color: #3261CE; margin: 24px 0 16px; padding-left: 12px; border-left: 4px solid #3261CE; font-weight: 500; } /* 内容项网格布局 */ .sub-content { display: grid; grid-template-columns: repeat(auto-fill, minmax(260px, 1fr)); gap: 20px; margin-top: 8px; } /* 内容项样式 */ .content-item { position: relative; height: 95px; cursor: pointer; border-radius: 8px; overflow: hidden; box-shadow: 0 3px 6px rgba(0, 0, 0, 0.03); transition: all 0.4s cubic-bezier(0.25, 0.8, 0.25, 1); background: #fff; border: 1px solid #e5e6eb; /* 背景图片容器 */ .img-wrapper { position: absolute; top: 0; left: 0; width: 100%; height: 100%; z-index: 1; opacity: 0; transform: scale(1.05); transition: all 0.5s cubic-bezier(0.22, 0.61, 0.36, 1); img { width: 100%; height: 100%; object-fit: cover; filter: blur(0); transition: filter 0.5s ease; } } /* 悬停效果 */ &:hover { transform: translateY(-5px); box-shadow: 0 12px 25px rgba(22, 93, 255, 0.2); border-color: rgba(22, 93, 255, 0.3); .img-wrapper { opacity: 1; transform: scale(1); img { filter: blur(4px) brightness(0.9); } } .item { background: rgba(255, 255, 255, 0.85); backdrop-filter: blur(4px); } .item-image img { transform: scale(1.8); } } } /* 内容卡片样式 */ .item { display: flex; position: relative; overflow: hidden; border-radius: 8px; width: 100%; height: 100%; z-index: 2; background: rgba(255, 255, 255, 0.95); transition: all 0.4s cubic-bezier(0.25, 0.8, 0.25, 1); } /* 图片样式 */ .item-image { width: 100px; height: 100%; flex-shrink: 0; overflow: hidden; display: flex; align-items: center; justify-content: center; background: #f7f8fa; transition: background 0.3s ease; img { width: 60px; height: 60px; object-fit: contain; display: block; transition: transform 0.5s cubic-bezier(0.22, 0.61, 0.36, 1); } .image-placeholder { width: 100%; height: 100%; display: flex; align-items: center; justify-content: center; color: #c9cdd4; .arco-icon { font-size: 32px; } } } /* 文本区域样式 */ .item-text { flex: 1; padding: 16px 12px; display: flex; flex-direction: column; justify-content: center; overflow: hidden; } .item-title { font-size: 16px; color: #1d2129; font-weight: 500; margin-bottom: 6px; white-space: nowrap; overflow: hidden; text-overflow: ellipsis; transition: color 0.3s ease; } .item-desc { font-size: 13px; color: #86909c; display: -webkit-box; -webkit-line-clamp: 2; -webkit-box-orient: vertical; overflow: hidden; text-overflow: ellipsis; line-height: 1.5; transition: color 0.3s ease; } /* 响应式调整 */ @media (max-width: 992px) { .container { flex-direction: column; } .tabs { width: 100%; position: sticky; top: 0; z-index: 30; display: flex; overflow-x: auto; padding: 10px 0; height: auto; border-right: none; border-bottom: 1px solid #e5e6eb; .tabs-wrapper { display: flex; padding: 0 16px; } .tab { flex-shrink: 0; margin: 0 8px; padding: 0 16px; height: 36px; line-height: 36px; } } .content { margin-left: 0; } .search-header { padding: 12px 16px; flex-wrap: wrap; } .section-container { padding: 0 16px; height: calc(100vh - 140px); /* 调整移动端高度 */ } .section { padding: 24px 0; } } @media (max-width: 576px) { .sub-content { grid-template-columns: 1fr; } .header-title { display: none; } .search-header { :deep(.arco-form-item) { width: 100%; margin-bottom: 12px; } } .section-container { height: calc(100vh - 180px); /* 调整小屏幕高度 */ } .content-item { height: 110px; } .item-image { width: 80px; } } </style>在这个代码基础上修改
最新发布
07-29
环境配置 Node 下载地址http://nodejs.cn/ 安装文件下有一个绿色的图片交node.exe 点击运行 输入node -v进行检测是否安装成功 使用vue-cli(脚手架)搭建项目 vue-cli是vue官方提供的用域搭建基于vue+webpack_es6项目的脚手架工具 在线文档:https://github.com/vuejs/vue-cli 操作: 1.npm install -g vue-cli:全局下载工具 2.vue init webpack 项目名:下载基于webpack模板项目 3.cd 项目名:进入项目目录 4.npm install :下载项目依赖的所有模块 5.npm run dev :运行项目 6.访问项目:localhost:8080 项目目录结构 src assets:存放照片、css、js css js img components:存放组件 lib:存放模拟数据 router:配置路由 store:存放vuex vuex的安装:cd x项目目录 cnpm install vuex --save views:存放所有单页面 配置访问端口号: 根目录下有一个config文件夹,看名字就知道配置有关,打开config目录下的index.js dev: { env: require('./dev.env'), port: 8092, autoOpenBrowser: true, assetsSubDirectory: 'static', assetsPublicPath: '/', proxyTable: {}, } 项目目录下:https://blog.csdn.net/weixin_39378691/article/details/83784403 1.安装elementUI:cd进入项目根目录,npm i element-ui -S 2.引入elementUI组件(main.js文件中) import Element from 'element-ui' import 'element-ui/lib/theme-chalk/index.css' Vue.use(Element, { size: 'small' }) 项目目录下:https://blog.csdn.net/weixin_41432849/article/details/81988058 1.安装jquery:cd进入项目根目录, npm install jquery --save 2.在项目 build 里的webpack.base.conf.js 里加载webpack文件,注意,要放在配置文件第一行; const webpack = require('webpack') 3.在module.exports的最后加入 , plugins:[ new webpack.ProvidePlugin({ $:"jquery", jQuery:"jquery", jquery:"jquery", "window.jQuery":"jquery" }) ]
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

漠媂

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值