What is the best way to navigate to a component that has been imported in Vue.js?

I have knowledge of Vue's scrollBehavior function, but I am struggling to integrate it with my existing code.

On my Index page, I have sections composed of imported Vue components like this:

<template>
  <div class="Container">
   <About />
   <Services />
   <Contact />
  </div>
</template>

The Navbar on my site contains links to these components:

    <template>
    <nav>
    <img class="nav__logo" :src="navLogo" height="40px" width="auto">
        <ul class="nav__row" ref="nav">
            <div class="nav__row__dropdown-toggle-btn" @click="toggleNav">
                <img :src="navMenuIcon" height="40px" width="auto">
            </div>
            <li class="nav__list-item" v-for="(link, index) in navLinks" :key="index"
                @mouseover="hover = true"
                @mouseleave="hover = false"
                :class=" { active: hover } ">
                <router-link :to="link.path">
                    {{ link.text }}
                </router-link>
            </li>
        </ul>
    </nav>
</template>

This information is sourced from the script in my App.vue file:

    <script>
import Navbar from '@/components/Navbar'
import Footer from '@/components/Footer'
export default {
  components: {
    Navbar,
    Footer
  },
  data: () => ({
    navLinks: [
      {
        text: 'Home',
        path: '/'
      },
      {
        text: 'About',
        path: '/about'
      },
      {
        text: 'Contact',
        path: '/contact'
      },
      {
        text: 'Services',
        path: '/services'
      }
    ]
  })
}
</script>

Currently, when I click on "About," it redirects me to a separate page for the "About" component. However, I want the page to scroll down to the About component embedded in my Index page upon clicking "About."

How can I achieve this? Do I need to make changes to the path?

Answer №1

Have you considered the concept of a router where the About components are treated as pages? By clicking on the component, it redirects to that specific page and changes the URL accordingly.

To achieve this functionality, I recommend utilizing pure JavaScript.

Start by assigning an ID to the About component (or use Vue ref if preferred).

 <template>
      <div class="Container">
       <About id="about"/>
       <Services />
       <Contact />
      </div>
    </template>

Next, link a method to the click event of the navigation menu.

 <li class="nav__list-item" v-for="(link, index) in navLinks" :key="index"
                @mouseover="hover = true"
                @mouseleave="hover = false"
                :class=" { active: hover } ">
                @click=nav(link)
            </li>


data: () => ({
    navLinks: [
      {
        text: 'About',
        id: 'about'
      }
    ]
  }),

methods:{
  nav(link) {
          const position = document.getElementById(link.id).offsetTop;
          // smooth scroll
          window.scrollTo({ top: position, behavior: "smooth" });  
   }
}

If using Vue ref, replace all IDs with refs. Use

this.$refs[link.id].$el.offsetTop
instead;

Answer №2

This video was extremely helpful to me as I learned how to scroll between components on the same page. The concepts can be applied in many different situations as well.

Check out the video here!

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Exploring the capabilities of chromaprint.js within a web browser

I'm currently in the process of developing a music streaming platform and I'm looking to include the chromaprint.js library for deduplication purposes. In my workflow, I utilize browserify and gulp. Despite the fact that the library claims it ca ...

Unable to invoke the 'apply' method on an undefined object when configuring directions for the jQuery Google Maps plugin

I've gone through the steps in a tutorial to create a jquery mobile google map canvas here, and have attempted to set it up. However, I keep encountering this error in my JavaScript console: Uncaught TypeError: Cannot call method 'apply' ...

Learn the method of conditionally resetting the state count using React hooks

When a user submits the form, the handleSubmit function runs to count the number of li elements with class names containing "show" within the search results div. It adds up these counts using setStoreCount(prevCount => prevCount + 1) and updates the UI ...

showing images received via a websocket connection

My current setup involves receiving one image per second through a WebSocket connection. The images are in blob format, and I am unsure of the best way to display them. Should I use an image tag or a video player? And how should I go about showing these ...

The property this.props.Values is not defined

I'm facing an issue with a page. Specifically, I am working with the value: this.props.CategoriesList. This value represents a list of categories. The problem is that when I click on a button to navigate to the page where this value is used, it shows ...

Tips for sending JSON data to the line chart function

Creating a line chart using Highcharts involves retrieving values from a database and passing those values to the line chart. Here is an example: //categories: ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun ...

Enhance your Nuxt.js website with a dual layout design option for each page

As a newcomer to Nuxt.js, I am currently in the process of transitioning a Vue project to Nuxt.js. My goal is to implement two different layouts on a single page: the default layout and a secondary one called the settings bar. In the settings page, I hav ...

What are the steps to creating a unique event within an AngularJs service?

In the midst of my AngularJs project, I find myself faced with a dilemma. I have a service designed to manage button events, but I want another service to handle these events indirectly without directly interacting with the buttons themselves. So, my goal ...

Out of nowhere, jQuery suddenly fails to recognize that my checkbox has been selected

http://pastebin.com/r30Wfvi3 Out of the blue, all that functionality suddenly ceased. var showMyLocation = document.createElement('input'); showMyLocation.type = "checkbox"; showMyLocation.className = "checkboxForRange"; showMyLocation.id = "sh ...

What steps are involved in implementing Local fonts in theme UI for Next JS?

I am currently developing an application using next JS with [theme-UI][1]. However, I need to implement local or custom fonts in my project and I'm unsure of how to do this. Below is the current theming setup: const theme = { fonts: { ...

Tips for incorporating API-provided CSS values into AngularJS expressions for stylish card customization

I am in the process of creating unique Pokemon cards that pull data from an API. My question is, how can I apply specific CSS styling to each card directly from the API, similar to how I have utilized AngularJS to render the information? So far, I have su ...

Utilize HTTPS and HTTP with Express framework in node.js

Currently, I am utilizing the express (3.0) framework on node.js to handle routing in my application. While most of the application makes use of the http protocol, there is a specific route that I intend to serve exclusively via https. This particular par ...

Leverage webpack to dynamically import a specific file depending on the node environment

Currently, I am developing a Vue app using cli 3. However, I have encountered an issue with a third-party front end component that requires a config file. My goal is to use different files based on my node environment, such as tree.production.js and tree.d ...

Currently, I am encountering a problem as I attempt to iterate through a dynamic table

I have a table containing various elements. An example row is Jack Smith with multiple rows like this: col1 col2 col3 col4 col5 col6 col7 col8 jack smith 23 Y Y error error_code error_desc The table is ...

Sending a string data from client to a MongoDB database using Express.js and Node.js with the help of Sails framework

Need help with sending a string from client to mongoDB using Sails The "val" variable represents a string sent in real time from the client to the server database POST Form( is using HTML the best approach here? ) <!DOCTYPE html> <html> < ...

Creating a blueprint for my AJAX setup to effectively incorporate a callback function

I'm currently working with AJAX to fetch timezone information in a function, but I need it to return the result. I've come to realize that AJAX is asynchronous, so I require a callback function. Although I have seen examples, I am struggling to u ...

Verify the presence of installed software on the client's machine through ASP.Net

Does anyone have any recommendations on how to verify if an application is installed on the client side in an ASP.Net application? Since ASP.Net operates on the server side, I think it would need to be accomplished using some sort of client-side scripting ...

Is it possible to store an HTML element tag in a variable?

I've been learning JavaScript on w3schools and freecodecamp, but I stumbled upon something in w3schools that has me puzzled. Can someone please explain why this particular code snippet works? The variable "text" is declared as containing the string " ...

The passport authentication process is malfunctioning as there seems to be an issue with the _verify function

Having an issue and could use some assistance. I am currently implementing passport in my express application. While I am able to successfully register a user, I encounter an error when trying to log in. TypeError: this._verify is not a function at Str ...

Unable to get the Express.js Router functioning correctly on my server, even in a basic scenario

I am encountering an issue with using express.Router(). It was not functioning correctly in my application for serving JSON from MongoDB, so I attempted to simplify the scenario. However, I am receiving a 404 Not Found error in the request. What steps shou ...