Vue.js anchor for div inside the same component

I am developing a Vue.js application and it is difficult for me to bind the binding to a specific div inside the component.

I have the following anchor:

<a href="#porto" class="porto-button">Porto, Portugal</a>

and the following div:

<div id="porto" class="fl-porto">

I am using vue-router in hash mode.

The problem is that whenever I click the "porto-button" button, it redirects me to the "home" page ('/')

I am using Vue.js 1.X and I tried to use the history mode (URL without hashbang), but it gives me an error cannot GET '/page'while refreshing the page.

Am I doing something wrong? What can I do about this?

+10
source share
3 answers

-, , /#something "-".

, - :

//P.S. the code is written for Vue 2.
//You will have to adjust it to Vue 1.

//Your view:
<a class="porto-button" @click="scrollMeTo('porto')">Porto, Portugal</a>
...
<div ref="porto" class="fl-porto">
//Your code:
methods: {
  scrollMeTo(refName) {
    var element = this.$refs[refName];
    var top = element.offsetTop;

    window.scrollTo(0, top);
  }
}

:

  • ref , ,
  • , window.scrollY top .
  • :)

1:

jsfiddle https://jsfiddle.net/5k4ptmqg/4/

2:

, Vue 1 ref="name" el:name (docs), :

https://jsfiddle.net/5y3pkoyz/2/

+18

<router-link to="#leaders">Leaders</router-link>

<router-link :to="'#${subMenuItem.linkTarget}'" class="page-submenu-list__link">
                    {{subMenuItem.linkTitle}}
                </router-link>

routes:[],
scrollBehavior (to, from, savedPosition) {
    //https://router.vuejs.org/guide/advanced/scroll-behavior.html
    if (to.hash) {
            return { selector: to.hash }
        } else if (savedPosition) {
            return savedPosition;
        } else {
            return { x: 0, y: 0 }
        }
  }
+6

"scrollIntoView()"

, euvl , , :


    new Vue({
      el: '#app',
      methods: {
        goto(refName) {
            var element = this.$els[refName];
          element.scrollIntoView();
        }
      }
    })

If you want a fantasy and make the scroll smoother, you can even add the following:

element.scrollIntoView({ behavior: 'smooth' });

Please note that older browsers will require a polyfill.

0
source

Source: https://habr.com/ru/post/1671693/


All Articles