Vue-router is displaying only the root route

I've been working on vue-router for some time now, but I seem to have hit a roadblock. Despite going through numerous articles and documentation, I can't seem to find the solution.

Even after reading multiple tutorials on using vue-router, I'm still facing issues with my code.

Here's a brief overview of what I've done so far: I've created three components - Home, Login, and HelloWorld.

I've also defined three routes in my code.

Let me share the relevant snippets:

main.js:

import Vue from 'vue'
import App from './App.vue'
import VueRouter from 'vue-router';
// import Home from './components/Home.vue';
import HelloWorld from './components/HelloWorld.vue';
import Login from './components/Login.vue';


Vue.use(VueRouter)

Vue.config.productionTip = false


const router = new VueRouter({
  mode: 'history',
  base: __dirname,
  routes: [
    { path: '/hello', component: HelloWorld },
    { path: '/login', component: Login },
    { path: '/', component: App }
  ]
});


new Vue({
  router,
  render: h => h(App),
}).$mount('#app')

App.vue:

<template>
  <div id="app">
    <HelloWorld/>
    <Login />
  </div>
</template>

<script>
import HelloWorld from './components/HelloWorld.vue'
import Login from './components/Login.vue'

export default {
  name: 'app',
  components: {
    HelloWorld,
    Login
  }
}
</script>

<style>
#app {
  font-family: 'Avenir', Helvetica, Arial, sans-serif;
  -webkit-font-smoothing: antialiased;
  -moz-osx-font-smoothing: grayscale;
  text-align: center;
  color: #2c3e50;
  margin-top: 60px;
}
</style>
... (continues with similar content) ...

Neither of the routes are working as expected. Every time I try to navigate by changing the URL, the base route (i.e., /) is always displayed.

Furthermore, it keeps showing the App.vue component instead of the intended ones.

Any help or insights would be greatly appreciated!

Answer №1

Your app.vue template is lacking the router's component <router-view/>, Try adding this:

<template>
  <div id="app">
    <router-view/>
  </div>
</template>

Remember that the <router-view/> tag is where your pages/components will be displayed.

Additionally, the base route / in your routes array is incorrect. The App component serves as the root component and should not be one of the routes but rather hold other pages or components as its children.

Answer №2

It appears that the missing piece in your puzzle is the <router-view/> tag within App.vue. The purpose of <router-view/> is to dynamically render components based on the URL, eliminating the need to manually import each component.

Give this a try:

<template>
  <div id="app">
    <router-view/>
  </div>
</template>

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

The process of generating collection names dynamically based on user information

My goal is to enhance the structure of my data collection and make it more organized. While I am familiar with accessing and retrieving data, I am unsure about creating the schema. Here is my current schema: var MySchema = new Schema ({ event: { ...

Transmitting special symbols through Socket.io

I've been working on a small project based on Socketio 0.9 and everything is running smoothly, except for a minor problem with special characters. In the web client, I am creating a dynamic JSON object using JavaScript that is then emitted to the ser ...

Using Vue along with bootstrap-vue: Ensuring only one list element is expanded in a list (v-for) at any given time

In my Vue project with bootstrap-vue, I am utilizing the b-collapse feature within a v-for loop for lists. While it is functioning correctly, I am struggling to automatically close expanded list elements when a new one is clicked. Here is my question: Ho ...

Leveraging em units in jQuery Script

I'm currently in the process of building a website and I'm facing an issue with converting measurements to em's. The script that I have reused from a previous project only seems to work with pixels, despite my efforts to make it compatible w ...

In a production environment, an ENOENT error in Next.js was triggered by fs.readdirSync

Utilizing the Next.js App Router, I attempted to retrieve all my markdown posts stored in files by scanning a directory using fs.readdirSync(). While everything worked flawlessly locally, upon deploying on Vercel, an unexpected issue arose. The code was e ...

Is the javascript function I created not recognized as "a function"?

A small .js file containing 3 functions for easy in-site cookie management was created. Below is the source code: // Create Cookie function Bake(name,value) { var oDate = new Date(); oDate.setYear(oDate.getFullYear()+1); var oCookie = encodeURIComponent(n ...

JavaScript-powered horizontal sliderFeel free to use this unique text

I'm new to JS and trying to create a horizontal slider. Here's the current JS code I have: var slideIndex = 0; slider(); function slider() { var i; var x = document.getElementsByClassName("part"); for (i = 0; i < x.length; i++) { x[i].styl ...

use ajax to dynamically append a dropdown menu

Currently working on creating a form that includes a dropdown menu populated with elements from a database. The challenge I'm facing is ensuring that once an element is selected from the dropdown, another one appears dynamically. My goal is to use AJA ...

Retrieving selected options from a jQuery mobile multiselect for database storage

I'm currently working on extracting values from a select list in a jQuery mobile application. Here's the markup for my select element: <div data-role="fieldcontain"> <label for="stuff" class="select">Stuff:</label ...

Issues with Vue Carousel Sliding Functionality

I'm currently tackling a project that involves incorporating Vue Carousel for displaying product slides with both images and text on each slide. My goal is to have only 5 slides displayed per page, complete with navigation arrows and the ability to dr ...

What is the value of x in the equation 2 raised to the power of x equals 800

Similar Question: What is the reverse of Math.pow in JavaScript? 2^x=i If i is given, how can we determine x using Javascript? ...

Remove any unnecessary characters from the beginning of the string and keep track of the total number of spaces removed

How can I determine the number of characters that have been removed from the beginning of a string? This string is retrieved from a textarea input, and knowing this information will help me calculate the new position of the cursor selection. While $.trim( ...

Vue, anticipate the Watch

My application has a similar structure when it comes to architecture. computed(){ currentValue = this.$store.currentValue; } watch() { currentValue() = async function () { //perform asynchronous action } }, methods: { updateValue( ...

Expanding size on hover without affecting the alignment of surrounding elements

Imagine there are 10 divs on the page styled as squares, collectively known as the home page. Among these 10: 3 divs belong to the .event1 class, 5 divs belong to the .event2 class, and 2 divs belong to the .event3 class. <div class="boxes event1"> ...

Error message: Unchecked runtime error - Unable to retrieve data from the specified URL. The extension manifest must include permission to access this particular host. This issue is occurring in manifest

Can someone help me out? I keep on receiving the error messages Unchecked runtime.lastError: Cannot access contents of url. Extension manifest must request permission to access this host. and Unchecked runtime.lastError: Could not establish connection. Rec ...

the spillage exhibits only a thin streak of gray

My website is primarily a Single Page Website, however, there are specific pages that can only be accessed by registered users. On the website, there is a section referred to as a "block" where you will find a button labeled "Login / Register". Upon clicki ...

Is it possible to test a Node CLI tool that is able to read from standard input with

I'm looking for a way to test and verify the different behaviors of stdin.isTTY in my Node CLI tool implementation. In my Node CLI tool, data can be passed either through the terminal or as command line arguments: cli.js #!/usr/bin/env node const ...

Assigning a session variable through a dropdown selection

Currently, I am working on a custom WordPress theme that involves setting a session variable based on the value selected from a dropdown box. This session variable is then used to determine which container should be loaded. The code snippet below shows whe ...

Effectively monitoring coordinates on both the client and server sides

I'm currently in the process of developing a multiplayer game using websockets, node, and JavaScript. I need advice on the most effective approach to update client information and manage their coordinates on the server. The method I am using at the mo ...

Utilizing JavaScript to transition a grayscale thumbnail image to vibrant color

I am a beginner in the world of web development and I have no idea how to begin coding a JavaScript function that will smoothly transition a grayscale thumbnail image into a color thumbnail image when the user hovers their mouse over it, and then back to g ...