Navigating to a specific div within a component in Vuejs 2: Steps for routing

These are the routes I've set up for my application:

const router = new VueRouter({
mode:'history',
routes:[
    {
        path:'/home',
        name:'home',
        component: Home
    },
    {
        path: '/services',
        name: 'services',
        component: Services
    },
    {
        path:'/blogs',
        name:'blogs',
        component:Blogs
    },
    {
        path:'/pingme',
        name:'pingme',
        component:Pingme
    }
],

It's now my goal to navigate to a specific div within the services route when the link is clicked. Specifically, I want to navigate to the services div within the Home component. How can I adjust my router settings to achieve this?

Answer №1

If you want to emphasize a specific div within the Service component, you can utilize query parameters for this purpose. Additionally, you can create a dedicated URL that accomplishes the same goal.

Here is an example of a route:

{
    path: '/services',
    name: 'services',
    component: Services
}

Next, in the URL

localhost:8000/services?show=mydiv
, within the mounted hook of the component, you can implement the following script:

mounted() {
  // Add an ID to the targeted div for focus
  // Pass the ID through the query parameter
  document.getElementById(this.$route.query.show).scrollIntoView()
}

Please let me know if this method works for your needs.

Edit

An alternative approach to achieve the same result involves using a watcher and a computed property.

Start by creating a computed property for the 'show' query parameter in the route.

computed: {
  show() { return this.$router.query.show }
}

Then, set up a watcher to trigger the focus behavior.

watch: {
  show: {
    immediate: true,
    handler(value) { 
      document.getElementById(value).scrollIntoView();
    }
}

This method should be effective in all scenarios.

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

D3 - Rounded edge chart width

Currently facing an issue with the chart where the data value is small, resulting in an 'ear' effect. Can anyone help me with this problem? Below is the code I am currently using: const rx = 30; const ry = 30; svg ...

Is the `beforeEach` function in Jasmine synchronized?

Is it guaranteed that multiple beforeEach functions will always run sequentially? beforeEach(function() {}); beforeEach(function() {}); beforeEach(function() {}); beforeEach(function() {}); beforeEach(function() {}); It appears they do. I conducted a tes ...

Leverage variables in Ajax to retrieve the data of an HTML element

Seeking assistance in converting multiple lines into a single for loop. var optie1 = ""; if($('#form #optie1_check').is(':checked')) { optie1 = $('#form #optie1_naam').val(); } var optie2 = ""; if($('#form #optie2_ch ...

Utilizing a JavaScript variable to fetch a rails URL: A comprehensive guide

One interesting feature I have is an image link that has a unique appearance: <a href="#user-image-modal" data-toggle="modal" data-id="<%= image.id %>"><img class="user-photo" src="<%= image.picture.medium.url %>" alt="" /></a&g ...

Unable to retrieve information from localhost site using the expressjs API. I have attempted to use both vue-resource and axios in order to get the data without success

Currently diving into the world of VueJS, I decided to embark on a project. My aim is to retrieve data from an ExpressJS server/API. But unfortunately, both vue-resource and axios have been returning status code 0. It seems like my API might not be handli ...

Any suggestions on how to incorporate the variable into the inline JavaScript [[]] API path?

I have a query regarding creating a URL in JavaScript, but I'm unsure how to include variables within th:inline="javascript". Below is my code snippet: <script th:inline="javascript"> $(function() { $('#querySubmit').click(queryS ...

React.js TypeScript Error: Property 'toLowerCase' cannot be used on type 'never'

In my ReactJS project with TSX, I encountered an issue while trying to filter data using multiple key values. The main component Cards.tsx is the parent, and the child component is ShipmentCard.tsx. The error message I'm receiving is 'Property &a ...

Show only the lower left quadrant within the img tag during the prepend operation

I'm attempting to add an <img> tag in front of a <div> similar to this example on JSFiddle. However, I have a specific requirement to only display the bottom left quarter of the image instead of the entire one. HTML Markup <div id="my ...

"Put Jest to the test by running it with the Express

Currently, I am in the process of learning how to build an API with TypeScript and experimenting with testing it using the Jest framework. When utilizing a basic Express application like app = express() supertest(app) everything works smoothly. However, ...

Numerous objects come into view as you scroll

I found a code snippet online that animates items as they appear on scroll. However, the code only triggers animation for one item at a time. How can I modify the code to trigger the animation for all items? const observer = new IntersectionObserver(e ...

The JSON object was not found in the AJAX response

I received a JSON object through an AJAX request. When I use console.log(response); in the console, I can see my object. However, when I use console.log(response.mostSearched);, it returns undefined. Why is that? I copied the object from the devTools con ...

How to Specify ContentType for a New Window in JavaScript after Submitting MVC Form

When a link is clicked, I want to open a new window with content determined by a post to my MVC controller. Here's how I currently approach it: jQuery.ajax({ type: "POST", url: '/controller/mycontroller', data: { myd ...

Trouble arises with the MUI 5 date picker when inputFormat is included

When I select a date from the calendar, everything works fine. However, if I set inputFormat="yyyy/MM/dd" and manually type in the date, it doesn't recognize the date format properly. Instead, it treats the input as a string like 11111111111 ...

What sets returning a promise from async or a regular function apart?

I have been pondering whether the async keyword is redundant when simply returning a promise for some time now. Let's take a look at this example: async function thePromise() { const v = await Inner(); return v+1; } async function wrapper() ...

Having difficulty in loading Socket.io client .js file?

I am currently facing an issue deploying a socket.io chat on Heroku. While the page loads successfully, the client's socket.io js file is not being downloaded, resulting in the chat functionality not working. Attached are images showcasing the error ...

What is the method for adding data to a table without utilizing an ID field?

Here is the code I have written: This table contains details of the candidates: <table id="candidates-table" class="table table-striped table-bordered"> <thead class="thead-dark"> <tr> <th scope="col">Candidate Picture ...

"Exploring the challenges of implementing a jquerytools tooltip with AJAX

Currently, I have set up an ajax call to run every 15 seconds. The issue arises when the ajax call disables the tooltip if it's open at that moment for a particular item. This results in the destruction of only the tooltip being displayed, leaving oth ...

Forcing a property binding update in Angular 2

Take a look at this particular component import {Component} from 'angular2/core' @Component({ selector: 'my-app', providers: [], template: ` <div> <h3>Input with two decimals</h3> <input type ...

What is the best method to update numerous low-resolution image sources with higher resolution images once they have finished loading?

I'm currently developing a website that implements a strategy of loading low-resolution images first, and then swapping them for high-resolution versions once they are fully loaded. By doing this, we aim to speed up the initial loading time by display ...

Generating a unique user ID similar to Zerodha's user ID using Node.js/JavaScript

For a project I'm working on, I need to create random and unique User IDs. I came across Zerodha's user IDs which are easy to remember. In Zerodha user IDs: The first two characters are always letters followed by four numbers. I want to generat ...