Guide on how to navigate to a new page using Vue JS Routers when clicking a specific link

Currently exploring Vue JS and running into difficulties with routers. I want specific content to display when entering a certain page address, such as "Home". For instance, I have a component named HomePage, and I desire for this component to appear when the URL contains "Home", like "http://localhost:8080/Home". If no specific address is provided, then an empty page should be displayed.

App.vue

<template>
    <HomePage></HomePage>
</template>

<script>
import HomePage from "@/View/HomePage/HomePage";
export default {
  name: 'App',
  components: {
    HomePage
  }
}
</script>

Edit

App.vue

<template>
    <HomePage>
      <router-view />
    </HomePage>
</template>

<script>
import HomePage from "@/View/HomePage/HomePage";

export default {
  name: 'App',
  components: {
    HomePage,
  }
}
</script>

Index.js

import Vue from 'vue'
import Router from 'vue-router'
import HomeRoute from '@/components/routes/HomeRoute'
import Rar from "./src/View/Rar";

Vue.use(Router)
const router = new Router({
    routes: [
        {
            path: '/home',
            name: 'HomeRoute',
            alias: '*',
            component: HomeRoute
        },
        {
            path: '/Rar',
            name: 'Rar',
            component: Rar
        }
    ]
})

export default router

Answer №1

To ensure proper navigation in your application, be sure to define specific paths within your routes setup. Here are the steps:

  1. Start by configuring your main app.vue file as follows:
    <div>
        <navbar />
        <router-view />
        <footer />
    </div>
</template>

  1. Create a folder named router and add an index.js file (or use a more structured approach). The contents of the index.js file should resemble the following:
import Vue from 'vue'
import Router from 'vue-router'
import HomeRoute from '@/components/routes/HomeRoute'
import AboutRoute from '@/components/routes/AboutRoute'

Vue.use(Router)
const router = new Router({
    routes: [
        {
            path: '/home',
            name: 'HomeRoute',
            alias: '*',
            component: HomeRoute
        },
        {
            path: '/about',
            name: 'About',
            component: AboutRoute
        }
    ]
})

export default router 

The initial path is designated as '/home' with an alias of *. When entering '/home' in the URL, it will direct you to the main page. Additionally, the alias: '*' setting signifies that any additional input in the URL will redirect to this route, unless matched with another registered route.

Answer №2

It seems like there is a code issue in your main.js file.

I don't see Vue being initialized anywhere in the code snippet.

Make sure to import the router in your main.js file and use .use(router) within it.

In your App.vue file:

<template>
  <router-view />
</template>

In your /router/index.js file:

import Router from 'vue-router'
import HomeRoute from '@/components/routes/HomeRoute.vue'

const router = new Router({
  routes: [
    {
      path: '/home',
      component: HomeRoute
    }
  ]
})

export default router

In your main.js file:

import Vue from 'vue'
import App from "./App.vue";
import router from '@/router'
const app = Vue.createApp(App)
app.use(router)
app.mount('#app')

Answer №3

Take a look at your HomePage component. Does it include a slot where you can place the router-view? Have you tried using a simple router-view without the need for HomePage? Make sure you have registered the router in your main app.js file.

If I understand correctly, you can manage your routes in index.js like this:

const router = new Router({
        routes: [
            {
            path: '/',
            beforeEnter: (from, to, next) => next({path: '/home'})
        },
        {
            path: '/home',
            name: 'HomeRoute',
            component: HomeRoute
        }
    ]
})

Explore VueRouter hooks here: https://router.vuejs.org/guide/advanced/navigation-guards.html#global-before-guards

You can also utilize children routes as shown below:

import HomeLayout from '@/layouts/HomeLayout.vue'
import HomePage from '@/views/HomePage.vue'
import HomeAbout from '@/views/HomePage.vue'

const router = new Router({
routes: [
    {
        path: '/',
        beforeEnter: (from, to, next) => next({path: '/home'})
    },
    {
        path: '/home',
        component: HomeLayout,
        children: [
            {
                path: '',
                name: 'Home',
                component: HomePage
            },
            {
                path: 'about',
                name: 'HomeAbout',
                component: HomeAbout
            }
        ]
    }
]

})

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

Undefined index when decoding JSON data

When calling the save function, a $.post is sent to 'upp.php' as follows: function save(){ var oldItems = JSON.parse(localStorage.getItem('itemsArray')) || []; var newItem = {}; var num = document.getElementById("num").value; newIte ...

Retrieve the value of an attribute within a controller function that is not a directive

Here is some HTML content, <button data-href="helloworld">Show href Value</button> And here is some Javascript content, $("body").on('click', 'button', function(){ console.log($(this).attr("data-href")); }); When exe ...

The type does not have a property named 'defaultProps'

I have a Typescript React class component structured like this: import React, { Component } from 'react'; interface Props { bar?: boolean; } const defaultProps: Partial<Props> = { bar: false, }; class Foo extends Component<Props& ...

Extracting information from this array using JavaScript

After struggling for a day, I finally managed to get some output from PHP instead of just the word "array". What a relief! (check out this link for the solution) Basically, this is the data returned from an XMLHTTP request to PHP, handled through a JS ca ...

Utilizing Vue to pinpoint the DOM element of another component: Steps for success

Upon clicking the sidebar icon in Sidebar.vue component: <i class='bx bx-menu' v-on:click="toggleMenu()" id="btn"></i> I want to toggle the classes of elements in different components: methods: { toggl ...

The fetch() POST request is met with an error message stating "415 Unsupported Media Type"

I keep encountering a 415 error when attempting to upload a PDF file using fetch(). The PDF file resides in the same directory as the js file, and the name is correct. async function uploadFile(filePath, extension, timestamp) { const url = "https ...

Try utilizing a variety of background hues for uib progressbars

Looking to incorporate the ui-bootstrap progressbar into my template in two different colors, background included. My initial idea was to stack two progress bars on top of each other, but it ended up looking too obvious and messy, especially in the corner ...

Is there a way to transform a JSON object into a custom JavaScript file format that I can define myself?

I have a JSON object structured as follows: { APP_NAME: "Test App", APP_TITLE: "Hello World" } My goal is to transform this JSON object into a JavaScript file for download. The desired format of the file should resemble the follo ...

Memory leaks observed in BinaryJS websockets

Currently, I am in the process of developing a simple client/server setup to facilitate the transfer of image data between a browser and a node.js server using BinaryJS websockets. Despite following the API examples closely, it seems that my implementatio ...

The event "subscriptionRemoved" is not being triggered when a password change is made on the Microsoft Graph API

Utilizing the Microsoft Graph API, I have set up subscriptions to receive notifications for calendar events through Node.js. As per the guidelines outlined in the documentation on Enhancing notification reliability for Outlook resources (preview), it speci ...

Google Cloud Endpoints API Encounter 404 Error

Scenario Currently, my setup involves AppEngine Cloud Endpoints using a Bootstrap JavaScript UI along with a Google SQL Datastore. Issue The problem arises when the Javascript tries to call gapi.client.load and receives a 404 error. Surprisingly, the ...

Ways to Implement an Origin's First-Party Cookies While Using it as a Third-Party

Imagine I am the owner of a website called "treat1creator.com". I want my clients, who are also website owners, to send HTTP requests to my server that contain cookies I have generated. Here is how it works: User "Sally" visits my site at treat1creator.co ...

What is the best way to identify and retrieve the objects that do not match when comparing two arrays of objects

obj1 represents the original object while obj2 symbolizes the modified object. The goal is to extract the key-value pairs and types for all changed objects within the obje2 array of objects. Therefore, I am looking for a solution where if the values for " ...

Discovering WebElements nested within other WebElements using WebdriverJS

Looking at this HTML structure <div> <div> <p class="my-element"></p> </div> <div> <div> <div> <p class="the-text"> I want to retrieve this text</p> </div> </div> <div> ...

What's the most effective method for incorporating Vue.js into a .NET Core (2.1) project?

When it comes to incorporating Vue.js into a .NET Core (2.1) project using Visual Studio 2017, there are several options available: You can use Vue CDN. More information at this link. Another option is to utilize libman and add the Vue.js library. Learn ...

The Else clause is executing twice in the jQuery code

https://jsfiddle.net/mpcbLgtt/2/ Creating a function that adds card names to an array named deck and their IDs to another array called cardIds when a div with the class "card" is clicked. The cards available are: <div class='card' id=' ...

During the second request, Ajax is unable to retrieve any data

Currently, I am working on a calendar project where I utilize an ajax request upon page load to fetch data from the rails database. Initially, the ajax call successfully retrieves the object during the page load event. However, when I attempt to retrieve ...

Memory Match: Picture Edition

In this memory game, letters are used. I had considered changing it to a picture-based game, but I faced difficulty in generating images and incorporating them into the array. <script> var memory_array = ['A', 'A', 'B&ap ...

Tips for using useState with dependencies on custom objects such as { filter[], sort[] }:

I am trying to use the useState Hook with a custom object that contains two arrays as shown below const [initConfig, setInitConfig] = useState<>({filter:[], sort:[]}); However, I am unsure of how to declare inside the angle brackets. The filter arr ...

What can Cordova and express js bring to the table together?

I'm feeling pretty lost when it comes to displaying express views in a Cordova app client. It seems like the app would have to send a GET request and then the express application would render the view. But I'm unsure about how to actually make t ...