I'm a beginner with vue (vue 3). I'm testing a mock vue application, and after testing the default homepage, i wanted to test how to make 2 (or more) different pages. However, what i do doesn't work, even though i'm following tutorials to the letter.
Context:
Expected result: after having configured 2 routes, accessing route 1 gives me a webpage. Accessing route 2 gives me another page.
Current result: whichever route/path i try to access, i am always presented with the default/initial page (The "App" page use at the initialization const app = createApp(App)
). My second page is never displayed. No error is displayed.
Project structure:
/src
|- main.js
|- components/
|- router/
|- router.js
|- views/
|- App.vue
|- App2.vue
main.js:
import { createApp } from 'vue'
import App from './views/App.vue'
import router from "./router/router"
const app = createApp(App)
app.use(router)
app.mount('#app')
router.js:
import { createWebHistory, createRouter} from 'vue-router'
import App from '../views/App.vue'
import App2 from '../views/App2.vue'
const routes = [
{
path: '/',
component: App
},
{
path: '/toto',
component: App2
}
]
const router = createRouter({
history: createWebHistory(),
routes
})
export default router
App.vue and App2.vue are vue files with noticably different content.
App.vue:
<script setup>
import HelloWorld from '../components/HelloWorld.vue'
</script>
<template>
<div id="nav">
<router-link to="/"> Home </router-link>|
<router-link to="/toto"> Toto </router-link>
</div>
<img alt="Vue logo" src="../assets/logo.png" />
<HelloWorld msg="Trying to make router work" />
</template>
(I omitted the css code which i assume to be irrelevant to the issue)
Issue:
I'm unable to find what i'm doing wrong.
If it helps: vite.config.js:
import { defineConfig } from 'vite'
import vue from '@vitejs/plugin-vue'
// https://vitejs.dev/config/
export default defineConfig({
plugins: [vue()]
})
Your missing to add the router-view
component which will contains your routed components:
<script setup>
import HelloWorld from '../components/HelloWorld.vue'
</script>
<template>
<div id="nav">
<router-link to="/"> Home </router-link>|
<router-link to="/toto"> Toto </router-link>
</div>
<img alt="Vue logo" src="../assets/logo.png" />
<HelloWorld msg="Trying to make router work" />
<router-view></router-view>
</template>