Vue跨页面或本页面锚点跳转定位

2,037 阅读1分钟

一、跨页面

a页面

点击跳转

<a href="javascript:void(0)" @click="goto('路径','b页面位置id')"> 跳转</a>

methods: {
//跳转方法 
    goto(page, selectID) { 
        console.log(this.$route.path, "this.$route.path"); 
        if (page == this.$route.path) { 
            //如果当前已经在这个页面不跳转 直接去 
            let toElement = document.getElementById(selectID); 
            toElement.scrollIntoView(true); 
            } else { 
            //否则跳转路由 
            localStorage.setItem("toId", selectID); 
            this.$router.push({ path: page }); 
         } 
     }, 
 },

b页面

跳转位置

<div id="productModel"></div>

created() {
    //创建时执行跳转锚点位置。如果导航也跳b页面注意冲突
    this.$nextTick(() => { 
        this.getlocal(); 
    }); 
},
methods: { 
    //从我本地找到id 
    getlocal() { 
        //找到锚点id 
        let selectId = localStorage.getItem("toId");
        let toElement = document.getElementById(selectId); 
        //如果对应id存在,就跳转 
        if (selectId) { 
            console.log(toElement, "toElement"); 
            toElement.scrollIntoView(true); 
        } 
    }, 
}, 
//离开页面进行对localStorage id销毁,避免其他入口进来有锚点问题 
destroyed() { 
    localStorage.setItem("toId", ""); 
},

二、本页面跳转

点击跳转

<a href="javascript:void(0)" @click="goto('路径','跳转位置id')"> 跳转</a>

跳转位置

<div id="productModel"></div>

//跳转方法 
methods: { 
    goto(page, selectID) { 
        console.log(this.$route.path, "this.$route.path"); 
        if (page == this.$route.path) { 
            //如果当前已经在这个页面不跳转 直接去 
            let toElement = document.getElementById(selectID); 
            toElement.scrollIntoView(true); 
        } else { 
            //否则跳转路由 
            localStorage.setItem("toId", selectID); 
            this.$router.push({ path: page }); 
         }
      }, 
    //从我本地找到id 
    getlocal() { 
        //找到锚点id 
        let selectId = localStorage.getItem("toId"); 
        let toElement = document.getElementById(selectId); 
        //如果对应id存在,就跳转 
        if (selectId) { 
            console.log(toElement, "toElement"); 
            toElement.scrollIntoView(true); 
        } 
    },
}, 
//离开页面进行对localStorage id销毁,避免其他入口进来有锚点问题 
destroyed() { 
    localStorage.setItem("toId", "");
},