Vue Router के साथ एंकर को स्क्रॉल करना

Dec 05 2020

मुझे जाने के लिए vuejs में एंकर लिंक सेटअप की आवश्यकता है:

<h1 id="apply">Test anchor</h1>

निम्नलिखित कार्य करता है लेकिन यह url को http: // localhost: 8080 / # / apply में बदल देता है

<a href="#apply" class="btn btn-primary mt-3">Apply Now</a>

यदि मैं पृष्ठ को ताज़ा करता हूँ तो यह नहीं पता कि कहाँ जाना है।

निम्नलिखित मेरे लिए भी काम नहीं करता है। यह #apply तक भी नहीं गिरता है।

<router-link to="/careers/job-1#apply">test</router-link>

मैं vuejs रूटिंग के साथ एंकर लिंक कैसे सेटअप करूं?

जवाब

1 Dan Dec 05 2020 at 07:51

अपनी संपत्ति में एक pathऔर एक hashसंपत्ति जोड़ें to:

<router-link :to="{ path: '/careers/job-1', hash: '#apply' }">test</router-link>

और scrollBehaviorअपनी राउटर परिभाषा में जोड़ें :

const router = new VueRouter({
  ...
  scrollBehavior (to, from, savedPosition) {
    if (to.hash) {
      return {
        selector: to.hash,
        behavior: 'smooth'
      };
    }
    return { x: 0, y: 0 };  // Go to the top of the page if no hash
  },
  ...
})

अब इसे behaviorहैश द्वारा परिभाषित एंकर को स्क्रॉल करना चाहिए (सुचारू रूप से, जब तक आप उस संपत्ति को हटा नहीं देते )