I'm a newbie to Vuejs and I'm wondering how I can load the component to App.vue depending on the route visited.
In my router -> index.js I have:
import { createRouter, createWebHistory} from 'vue-router'
import Events from '../views/Events.vue'
const routes = [
{
path: '/',
name: 'events',
component: Events
}
]
const router = createRouter({
history: createWebHistory(),
routes
})
export default router
In my App.vue I have a template that I want to use for the entire website, so I thought to load the template here instead of loading it into each component.
My template has 1 box in the center of the screen, so the content changes depending on which route the user goes to.
Instead of calling the component content from the routes file, is there a better way to load it dynamically into App.vue depending on the route visited?
I could hard code it in App.vue with something like:
<template>
<Events />
</template>
<script>
import Events from './views/Events.vue'
export default defineComponent({
components: {
Events
},
</script>
But that won't solve my problem about the Events component being loaded dynamically depending on which route is visited. Is there a way to access the underlying component with something like this.$route to load the component instead of hard coding it.
The router-view component will render the component based on its path :
<template>
<router-view/>
</template>
<script>
export default defineComponent({
})
</script>
Related
As part of my Quasar app, I have the following route:
import { RouteRecordRaw} from 'vue-router'
import { uid } from 'quasar'
const routes: RouteRecordRaw[] = [
{
path: '/',
redirect: () => {
console.log('matched /')
return {path: `/${uid()}`}
}
},
{
path: '/:uuid',
component: () => import('pages/User.vue')
// component: User,
},
];
export default routes;
This works fine when going to /: the URL is changed to /73a219e5-2cf2-4dd0-8... and User.vue is executed (specifically there a fetch inside that retrieves some data based on the :uuid parameter.
If I force a route from within a component (User.vue for instance), via
import { useRouter } from 'vue-router'
const router = useRouter()
router.push('/')
I do see that the URL changes to a new UUID but User.vue is not executed. Specifically, a reference to route.params.uuid where const route = useRoute() is not reactive.
Is this normal (= I have to look for anther way to trigger), or is there a misuse (erroneous use) on my side?
The core of the issue is that you're (re)using the same component for rendering the page you're navigating from and the page you're navigating to.
By design, Vue optimises DOM rendering and will reuse the existing component instance. This means certain hooks won't be triggered (e.g: mounted, created, etc...) when changing route.
To force Vue into creating a different component instance when the route changes, use the current route's .fullPath as key on <router-view>:
<template>
...
<router-view :key="route.fullPath"></router-view>
...
</template>
<script setup>
import { useRoute } from 'vue-router'
const route = useRoute();
</script>
As part of my Quasar app, I have the following route:
import { RouteRecordRaw} from 'vue-router'
import { uid } from 'quasar'
const routes: RouteRecordRaw[] = [
{
path: '/',
redirect: () => {
console.log('matched /')
return {path: `/${uid()}`}
}
},
{
path: '/:uuid',
component: () => import('pages/User.vue')
// component: User,
},
];
export default routes;
This works fine when going to /: the URL is changed to /73a219e5-2cf2-4dd0-8... and User.vue is executed (specifically there a fetch inside that retrieves some data based on the :uuid parameter.
If I force a route from within a component (User.vue for instance), via
import { useRouter } from 'vue-router'
const router = useRouter()
router.push('/')
I do see that the URL changes to a new UUID but User.vue is not executed. Specifically, a reference to route.params.uuid where const route = useRoute() is not reactive.
Is this normal (= I have to look for anther way to trigger), or is there a misuse (erroneous use) on my side?
The core of the issue is that you're (re)using the same component for rendering the page you're navigating from and the page you're navigating to.
By design, Vue optimises DOM rendering and will reuse the existing component instance. This means certain hooks won't be triggered (e.g: mounted, created, etc...) when changing route.
To force Vue into creating a different component instance when the route changes, use the current route's .fullPath as key on <router-view>:
<template>
...
<router-view :key="route.fullPath"></router-view>
...
</template>
<script setup>
import { useRoute } from 'vue-router'
const route = useRoute();
</script>
So using router/index.js I managed to at least get the home page displayed. Now I have moved the code to main.js to simplify it for this question, and not even the home page loads. I only get the vue logo:
main.js:
import { createApp } from 'vue'
import { createRouter, createWebHistory } from 'vue-router'
import App from './App.vue'
import Home from '#/pages/Home.vue'
import DiscussionPage from '#/pages/DiscussionPage.vue'
const routes = [
{
path: '/',
name: 'Home',
component: Home
},
{
path: '/discussion-page/:id',
name: 'DiscussionPage',
component: DiscussionPage,
props: true
}
]
const router = createRouter({
history: createWebHistory(),
routes
})
const forumApp = createApp(App)
forumApp.use(router)
forumApp.mount('#app')
Here's the template from the homepage (Home.vue inside src/pages):
<template>
<div class="home">
<p>This is the home page</p>
<div class="discussions" v-for="discussion in discussions" :key="discussion.id">
<router-link :to="{name: 'DiscussionPage', params: {id: discussion.id}}">
{{ discussion.word}}
</router-link>
</div>
</div>
</template>
There was no issues getting the discussions data before I added vue-router, is why I am not including that part of the code. Also, before I moved the code to main.js the url would change when clicking the router-link for the discussion page, but the page would not load.
I am using vue-router4 and I built the app using the CLI with the default vue3 option.
Any clues of what it is I am doing wrong? I am sure it is anobvious little detail, but I can't find it :-(
Thank you so much :-)
This was really silly, but I guess it is still worth publishing for beginners?
For the vue-router to work, one must add the router-view tag. I guess I could have added it in my home page as Bulent suggested. But I think it makes more sense to add it in App.vue so that affects the whole app.
I have to say that this is not clear at all from the current documentation: https://next.router.vuejs.org/guide/#router-link
So simply adding this on App.vue activated the router, and all works well now :
<template>
<router-view/>
</template>
I have a vue application which dose simple inserts and i am trying to use vue router to redirect to different pages for example when i load /postComponent and /userComponent they will be on separate pages not all in one page when loading the localhost:8080
app.js
<template>
<div id="app">
<router-link to="/postcomponent">post</router-link>
<router-link to="/usercomponent">user</router-link>
<router-view/>
</div>
</template>
<script>
import PostComponent from './components/postComponent';
import userComponent from './components/userComponent';
export default {
name: 'app',
components: {
PostComponent,
userComponent
}
};
</script>
routes.js
import Vue from 'vue'
import App from '/client/src/App'
import VueRouter from 'vue-router'
import postComponent from '/client/src/components/postComponent';
import userComponent from '/client/src/components/userComponent';
vue.use(VueRouter);
Vue.config.productionTip = false
const routes = [
{
path: '/postcomponent',
name: 'postcomp',
component: postComponent
},
{
path: '/usercomponent',
name: 'usercomp',
component: userComponent
},
];
new Vue({
routes,
render: h => h(App),
}).$mount('#app')
postComponent
<script>
import postService from '../postService';
export default {
name: 'postComponent',
data() {
return {
posts: [],
error: '',
topic: '',
price: '',
location: '',
provider: ''
}
},
index.js
const express = require ('express');
const bodyparser = require ('body-parser');
const cors = require ('cors');
const app = express();
app.use(bodyparser.json());
app.use(cors());
const posts = require('./api/posts');
const users = require('./api/users');
app.use('/api/posts', posts);
app.use('/api/users', users);
const port = process.env.port || 500;
app.listen(port, () => console.log(`Server started on port ${port}`));
im getting the following error
https://i.stack.imgur.com/42Ka3.png
UPDATE ** :
App.vue :
<template>
<div id="app">
<router-link to="/postcomponent">post</router-link>
<router-link to="/usercomponent">user</router-link>
<router-view/>
</div>
</template>
Inside Routes.js import statements and paths :
import PostComponent from "#/components/PostComponent";
import UserComponent from "#/components/UserComponent";
const routes = [
{
path: '/postcomponent',
name: 'postcomp',
component: PostComponent
},
{
path: '/usercomponent',
name: 'usercomp',
component: UserComponent
},
];
PostComponent :
<template>
Post Comp
</template>
<script>
export default {
name: "PostComponent"
}
</script>
User Comp :
<template>
User Comp
</template>
<script>
export default {
name: "PostComponent"
}
</script>
UPDATE * :
remove those unnecessary imports on app file
I think its better to first have a look at Vue-router at https://router.vuejs.org/
SPA stands for Single Page Application means that all of your components eventually will execute on a single *.html file. this means that in SPA, you cant just redirect your client to another url and perform another HTTP request and still be on the same Vue SPA!. because then you will probably get new html/css and javascript files to execute and render.all you can do is 1.use vue router to specify on which path, what component should render. when you describe your router using VueRouter thats exactly what you are going to do!, config your router and tells him on which path, what component you should render.
there is no way that you can redirect your client to another domain and still be on the same SPA and loads your components BUT !
as i can see in your codes there is a way to achieve what you want. there are some problems in your code but i'll show you how you can config two routes to achieve something like that.
i assume that you have those two components postComponent and userComponent ready.
first we have to import those in our routes.js :
import postComponent from 'PATH_TO_COMP';
import userComponent from 'PATH_TO_COMP';
note that you can use '#' as an alias for /src in your directory
first we have to specify two routes, for /postcomponent and /usercomponent,
we doing it by adding two objects to routes array in VueRouter, we can specify a name for our routes and we must specify a component which will render on that router,
routes : [
{path : "/postcomponent", name :"postComp", component:postComponent},
{path : "/usercomponent", name :"userComp", component:userComponent}
]
so now we have to implement our app file to say that where we want this components to render, we use empty <router-view/> tag to show that,
now everything is set, you can switch between routes using <router-link> tag like below :
<router-link to="/postcomponent" >Show me post component :)</router-link>
and you will see that when you go to http://localhost:8080/postcomponent your postComponent will render and sits on your <router-view/> !
I have a really simple minimal example page with vue-router which is only partially working.
app.js
import 'babel-polyfill';
import Vue from 'vue';
import VueRouter from 'vue-router';
import App from './app.vue';
import router from './router'
new Vue({
router,
render: h => h(App)
}).$mount('#app')
app.vue
<template>
<div class="container">
<div id="nav">
<router-link to="/">Page 1</router-link>|
<router-link to="/page2">Page 2</router-link>
<router-link to="/sretbs">No page</router-link>
</div>
<div style="border:5px solid green">
<router-view></router-view>
</div>
</div>
</template>
<script>
export default {};
</script>
router.js
import Vue from 'vue'
import Router from 'vue-router'
import Page1 from './page1.vue';
import Page2 from './page2.vue';
import ErrorPage from './error.vue';
Vue.use(Router)
export default new Router({
routes: [
{ path: '/page1', name: 'page1', component: Page1 },
{ path: '/page2', name: 'page2', component: Page2 },
{ path: '*', component: ErrorPage }
],
redirect: {
"/": "page1"
}
})
The <router-view> appear to work on first page load. It shows the component I expect for whatever route is currently in the url (e.g. localhost/test#/page2), or if I explicitly route.push before binding Vue to #app it also shows the expected component.
Navigating to other routes doesn't appear to fully work, or at least it's not rendering the new route. When I add debug output to the page components like so:
<template>
<div class="container">
<h2>this is page 2</h2>
<buttons></buttons>
</div>
</template>
<script>
export default {
beforeRouteEnter: function(to, from, next) {
console.log(`Entering page 2:`);
next();
},
beforeRouteLeave: function(to, from, next) {
console.log(`Leaving page 2`);
next();
},
beforeRouteUpdate: function() {
console.log(`Before route update`);
}
};
</script>
it is picking up the routeenter/leave events. I can seemingly navigate back and forth between routes, but you don't see the result until a page reload
I can't recreate the problem in a jsfiddle, and I've scrapped everything and started again but am getting the same result. I can't see anything I'm doing wrong from looking at the Vue Router documentation. Any idea what I'm missing here?
In this instance the answer was painfully simple. There was another Vue instance on the page elsewhere. Even though my understanding is separate Vue instances bound to different container elements should be able to exist in harmony, in this instance it wasn't. It was also what was breaking the Vue dev tools, showing a Vuex instance for example but not showing any of the loaded components and giving a Cannot read property '__VUE_DEVTOOLS_UID__' of undefined error in the Vue Dev Tools errors.