Search code examples
vue.jsvue-router

With newest version of Vue, Vue router is not working correctly


Vue Router does not seem to working with Vue "^3.5.4" (newest). Here is the code:

Main.js

import "bootstrap";
import "bootstrap/dist/css/bootstrap.css";
import 'vue3-carousel/dist/carousel.css'

import {BootstrapIconsPlugin} from 'bootstrap-icons-vue';

import {createMemoryHistory, createRouter} from 'vue-router'

import { createApp } from 'vue'
import App from './App.vue'


import AboutView from "@/components/AboutView.vue";
import FirstPage from "@/components/Layout.vue";
const routes = [
 { path: '/', name: 'Home', component: FirstPage },
 { path: '/about', name: 'about', component: AboutView },
]

const router = createRouter({
   history: createMemoryHistory(),
   routes,
 })

const app =createApp(App);
app.use(BootstrapIconsPlugin);
app.use(router);

app.mount('#app')

App.vue

 <template>
 <nav-bar></nav-bar>

 <p>Current route path: {{ $route.path }}</p>

 <Footer></Footer>
 </template>

<style scoped>
    br,body{
    background-color: coral;
    }
</style>


<script  lang="js">
   import NavBar from "@/components/NavBar.vue";
   import Footer from "@/components/Footer.vue";
  export default {
     components: {Footer, NavBar},
     data() {
       return {
         activeComp: false
       }
     },
     methods:{

     },
     mounted() {

     this.$router.push("/")
    }
 }


  
 </script>

Layout.vue

<template>
    <h1>Home</h1>
</template>

About.vue

<template>
    <h1>About</h1>
 </template>

The path in App.vue clearly shows that it is correct when the router link is clicked. But the view doesn't change or load properly. I have used Vue router in the past many times.

Any help will be appreciated! Thanks in advance.


Solution

  • You should use router-view component in order to render your current view :

     <template>
       <nav-bar></nav-bar>
    
       <p>Current route path: {{ $route.path }}</p>
       <router-view/>
       <Footer></Footer>
     </template>