vue點擊標籤滑動到對應模塊

vue點擊標籤滑動對應某個模塊

效果圖

在這裏插入圖片描述

html

<template>
    <main class="main">
        <!-- 遍歷標題 -->
        <ul class="navMenu">
            <li v-for="(item, index) in navList" :key="index" @click="showModule(index)" :class="{actives: active === index}">{{item.title}}</li>
        </ul>

        <!-- 遍歷模塊 -->
        <div class="contentWrap">
            <section :style="`background: ${item.color}` " :class="`commSty module${index}`" v-for="(item, index) in moduleList" :key="index+10">
                {{item.content}}
            </section>
        </div>
    </main>
</template>

Js

<script>
    export default {
        data(){
            return{
                navList: [
                    {"title": "推薦"},
                    {"title": "科技"},
                    {"title": "時尚"},
                    {"title": "新聞"},
                ],
                moduleList: [
                    {"content":"推薦推薦", "color":"red"},
                    {"content":"科技科技", "color":"yellow"},
                    {"content":"時尚時尚", "color":"pink"},
                    {"content":"新聞新聞", "color":"yellowGreen"},
                ],
                active: 0,
            }
        },  
        methods: {
             showModule(index) {
                console.log(index);
                
                // 給當前點擊元素添加類名
            	this.active = index;

                //獲取元素
                var el = document.getElementsByClassName(`module${index}`)[0];
                console.log(el.offsetTop);
                this.$nextTick(function () {
                    // 平滑滑動【這裏-55 是當前元素上邊界相對body的上偏移量】,可根據需求修改
                    window.scrollTo({"behavior":"smooth","top":el.offsetTop - 55 });
                })
            }
        }
    }
</script>

如需求是通過地址欄參數獲取的, 可使用watch監聽路由變化

watch: {
    '$route' (to, from) {
        // console.log('獲取點擊的參數---->', this.$route.query.current);
        let currentModule = this.$route.query.current;
        // 獲取當前操作模塊
        this.showModule(currentModule);
    }
},
created() {
    this.getCurrentParams = this.$route.query.current;
},
mounted() {
	if(this.getCurrentParams != undefined) {
        showModule(this.getCurrentParams);
	}
},  

scss

<style lang="scss" scoped>
   .main {
       overflow: hidden;
       .navMenu {
           display: flex;
           position: fixed;
           top: 0;
           left: 0;
           height: 55PX;
           width: 100%;
           background-image: linear-gradient(90deg, #fe650b 0%, #ff8451 100%);
           li {
               display: flex;
               align-items: center;
               justify-content: center;
               flex: 1;
               color: #fff;
           }
           .actives {
               color: red;
           }
       }
       .contentWrap {
           margin-top: 55PX;
           .commSty{
               width: 100%;
               height: 500PX;
           }
       }
   }
</style>
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章