Reputation: 3360
When the user navigates to a page using an alias of the route, the URL stays with the alias and the page is rendered correctly.
How could I change to URL to the path
when the user navigates to an alias?
import Vue from "vue";
import VueRouter from "vue-router";
import Home from "@/views/Home.vue";
Vue.use(VueRouter);
const routes = [
{
path: "/404",
name: "404",
alias: "*",
component: () => import(/* webpackChunkName: "NotFound" */ "@/views/NotFound.vue")
},
{
path: "/",
name: "Home",
alias: "/home",
component: Home
},
{
path: "/downloads",
name: "Downloads",
alias: ['/download', '/releases'],
component: () => import(/* webpackChunkName: "Downloads" */ "@/views/Downloads.vue")
}
];
const router = new VueRouter({
mode: "history",
base: process.env.BASE_URL,
routes
});
export default router;
For example:
www.example.com/home
.Home
page page.Other:
www.example.com/lalallaa
.NotFound
page page.What would be the best way to accomplish this? I can only think about using the created()
event on each page and manually setting the URL, but I'm not sure if it's the best way.
Upvotes: 2
Views: 1764
Reputation: 165065
What you want are redirects, not aliases.
Set up the known redirects you want like
/home
=> /
/download
and /releases
=> /downloads
and then add a catch-all redirect to /404
at the end of the routes
array.
const router = new VueRouter({
routes: [{
path: '/404',
component: { template: `<h1>404</h1>` }
}, {
path: '/',
component: { template: `<h1>Home</h1>` }
}, {
path: '/home', redirect: '/'
}, {
path: '/downloads',
component: { template: `<h1>Downloads</h1>` }
}, {
path: '/download', redirect: '/downloads'
}, {
path: '/releases', redirect: '/downloads'
}, {
path: '*', redirect: '/404'
}]
})
new Vue({
el: '#app',
router
})
<script src="https://cdn.jsdelivr.net/npm/vue/dist/vue.min.js"></script>
<script src="https://unpkg.com/[email protected]/dist/vue-router.js"></script>
<div id="app">
<ul>
<li><router-link to="/home">/home</router-link></li>
<li><router-link to="/">/</router-link></li>
<li><router-link to="/downloads">/downloads</router-link></li>
<li><router-link to="/download">/download</router-link></li>
<li><router-link to="/releases">/releases</router-link></li>
<li><router-link to="/lalallaa">/lalallaa</router-link></li>
</ul>
<router-view></router-view>
<pre>$route.fullPath = {{ $route.fullPath }}</pre>
</div>
Upvotes: 3