Cannot figure out how vue-router works - vue.js

I have a Vue.js project with the following router:
import Vue from 'vue';
import Router from 'vue-router';
import Overview from '#/components/Overview';
import Experiment from '#/components/ForExperiment';
Vue.use(Router);
export default new Router({
routes: [
{
path: '/',
redirect: 'test',
},
{
path: '/overview',
component: Overview,
},
{
path: '/overview/from/:from/to/:to',
name: 'overview',
component: Overview,
},
//... some other urls goes here.
{
path: '/test',
name: 'test',
component: Experiment,
},
],
});
If I open http://localhost:8080 in a browser I am redirected to http://localhost:8080/#/test. Why not just http://localhost:8080/test? Where does the '#' symbol come from?
And why if I open http://localhost:8080/test am I redirected to http://localhost:8080/test#/test?
And what is even more strange, if I open http://localhost:8080/overview I am redirected to http://localhost:8080/overview#/test, so the Overview component is not displayed.
What can cause these strange effects?

Vue router has different modes. The default mode when a browser is detected is hash. The current route is determined by the hash part of the url. The upside of this approach is that no serverside configuration is required. All urls point at the same resource (e.g. the route), which you can make your index.html file.
You can change this mode to history. The history mode uses the history api of the browser. It will only work in recent browsers, but support should not be an issue at this point. It will also require server side configuration in that you need to internally rewrite your router urls to the same file. If you would not do that, refreshing the page will show a 404 page instead of the page you want to see.

vue-router default mode is hash mode, that is why you see a # on your URL. It uses the URL hash to simulate a full URL without reloading the page if it changes.
To get rid of the hash, we can use vue-router history mode. Change the mode like so:
const router = new VueRouter({
mode: 'history',
routes: [...]
})
This leverages the History API.
If you want to use the history mode, you'll need to change your server configuration. Vue Router docs has some examples here.

The vue router defaults to hash mode. For your url to go to http://localhost:8080/test you need to go into history mode. This is done because by default web servers are not setup to redirect all requests to one html file. hash mode is used to per the docs:
The default mode for vue-router is hash mode - it uses the URL hash to simulate a full URL so that the page won't be reloaded when the URL changes.
Change your router to this to get history mode. But you will need to configure NGINX or Apache2 to redirect all requests to your vue code
const router = new VueRouter({
mode: 'history', // Add this to your router
routes: [...]
})

Related

Loading problems when sharing a link on a site with Vue

I' ve created a website that uses Vue as front-end framwork and the CMS CosmisJS to manage the content. My site uses, among other things, Vue Router, Vuex and Vue Meta and is hosted on Netlify.
My site works fine, you can navigate between the different routes and the information loads without problems, however, when I share a link with a route, for example, http://example.com/route, the page simply doesn't load and shows me a Netlify error that says "Page Not Found" even though the route exists and can be visited if you navigate from the root route.
I can't figure out where the problem is. I thought it might be an error related to load times with API calls or some error in my Vue Router configuration, but I have made changes and the problem still persists.
Any idea what it could be?
Here is a simplified version of my Vue Router.
import Vue from "vue";
import VueRouter from "vue-router";
import CentroEstudios from "../views/CentroEstudios.vue";
import Nosotras from "../views/Nosotras.vue";
import Index from "../views/Index.vue";
Vue.use(VueRouter);
const routes = [
{
path: "/",
name: "Index",
component: Index,
},
{
path: "*",
name: "NotFound",
component: NotFound,
},
{
path: "/centro-de-estudios",
name: "Centro de Estudios",
component: CentroEstudios,
},
{
path: "/nosotras",
name: "Nosotras",
component: Nosotras,
},
];
const router = new VueRouter({
mode: "history",
base: process.env.BASE_URL,
routes,
});
export default router;
This is a consequence of using history mode on the router.
https://router.vuejs.org/guide/essentials/history-mode.html
Here comes a problem, though: Since our app is a single page client side app, without a proper server configuration, the users will get a 404 error if they access http://oursite.com/user/id directly in their browser. Now that's ugly.
You need to configure Netlify to be compatible with history mode:
https://docs.netlify.com/routing/redirects/rewrites-proxies/#history-pushstate-and-single-page-apps
Here is another relevant post on the netlify support forum:
https://answers.netlify.com/t/vue-app-not-routing-correctly-when-deployed/6363
Or, if it's ok for the purposes of the website you're making, you can also just use the default hash mode and then you do not have this issue but you will have a hash before in all the URL paths.

vue.js and vue router. Why does the call of `new VueRouter() ` already modify the current URL?

I have a non SPA (multi page application). On one page I use a vue.js component with multiple tabs. I control those tabs with VueRouter. it all works well very well actually.
I am using vue 2 and vue-router 3.
I define the Router directly in the single file component like this.
<script>
// import Vue from 'vue';
import VueRouter from 'vue-router';
export default {
name: 'ProductDisplay',
router: new VueRouter({
routes: [
{ name: 'offer', path: '/' },
{ name: 'posts', path: '/posts' },
{ name: 'reviews', path: '/reviews' }
],
}),
}
</script>
This tabbed component is imported globally because the entire multipage application is driven by a single app.js file compiled by webpack.
My problem is now, that even on pages, where this component is not used at all (only import ProductDisplay from product-display.vue is present), this new VueRouter({}) call affects the current URL by appending /#/ at the end.
e.g. loading my homepage https://www.example.com it ends up beeing https://www.example.com/#/
Just to clarify: this ProductDisplay component is NOT used on the homepage at all.
On the other hand, on the page where ProductDisplay is being used I expect the urls to be like this and it works well.
https://www.example.com/product#/
https://www.example.com/product#/posts
https://www.example.com/product#/reviews
Here is the entire JavaScript code (webpack + babel) loaded on the homepage if someone likes to analyze. https://pastebin.com/VAAvpfXA
Is there a way to avoid this behaviour, e.g. by explicitely activating/initiating a VueRouter object?

Base option in vue router

This issue has been discussed several times (1 - 2) but I still cannot get it to work. I'm transitioning our project to use vue in some parts. What I want to accomplish is:
If url starts with /v/, look into vue router and match path.
If url starts with anything other than /v/, ignore it (this view will be rendered by current framework from backend).
My router looks like:
const router = new Router({
base: '/v/',
mode: 'history',
routes: routes
});
Where routes are:
const routers = [
...
{
path: '/wholesale-catalogue/',
name: 'wholesale-catalogue',
component: () => import('./views/WholesaleCatalogue.vue')
}
...
]
The second option I tried is nesting the children routes:
const router = new Router({
mode: 'history',
routes: [
{ path: 'v', component: BaseView, children: routers }
]
});
The problem is that the router reroutes non /v/ urls into /v/ when clicked within the website, such as:
ourwebsite.com/home/ -> has some links on it, such as /about/. When you click on /about/ it actually goes to ourwebsite.com/about/ for a few seconds but then the url changes to /ourwebsite.com/v/about/. This leads to some annoyances as when you refresh the website, this url doesn't exist (on our current backend framework) so it will not render.

Vue Routes does not work properly in production

I am new to vuejs. For my Vuejs application, I cannot access url like '/foo/apple' in the web hosting server, after I run the "npm run build". It shows error 404 I am using the HTML5 History Mode,(https://router.vuejs.org/guide/essentials/history-mode.html#example-server-configurations) and I implemented the "connect-history-api-fallback" like below in dev-server.js:
const express = require('express')
const app = express()
app.use(require('connect-history-api-fallback')())
My router/index.js
export default new Router({
mode: 'history',
{
path: '/Product',
name: 'Product',
component: Product,
},
{
path: '/Product/kraftbag',
name: 'Kraftbag',
component: Kraftbag
},
});
my website http://americandunnage.n55lwi.info/.
I have looked for a lot of posts regarding to this problem, but I still can find the solution.
you are likely missing the hashbang (#)
try #/foo/apple instead of /foo/apple
The default setting of the vue router is to use the hashbang method. This relies on using the index.html (or whatever defaults to / url) page, because everything after it is not taken as part of the url location but passed into the application. For example, in an anchor 1st heading this will go to a part of the page, and if you're already on that page, you will not be redirected.

VueJs 2: Unable to render view when using history mode and route params

I am trying to set up SPA routes using history mode as follows:
{
mode: 'history',
routes: [
{
path: '/',
component: Home
},
{
path: '/articles',
component: ArticleList,
children: [
{
path: ':title',
component: ArticleView
}
]
}
]
}
As I am using the history mode routing on vue and on express application I've set up "express-history-api-fallback" as the last middleware in the pipeline:
const app = express();
const root = path.join(__dirname, '../client/dist');
app.use(express.static(root));
/* other middlewares */
app.use(fallback('index.html', {root: root}));
At the moment of a page reload, everything works fine. I.e. loading a url http://application/articles, opens correctly the view, BUT when I try to access the view that takes in a parameter, no matter what, the view does not get loaded and two requests are made to the express.
I.E. a request to http://application/articles/test will resolve into two requests. One to http://application/articles/test and another one to http://application/articles/app.[calculated-hash].js
As far as I understand, the first request fetches the index.html the other request fetches the bundled js script.
Also, on the express app, all routes to api start with 'api' prefix.
Question:
What is wrong with my setup/code using history mode and route params because no routes with parameters are loaded when trying to access them when entering url manually or hitting refresh?
Update:
Using connect-history-api-fallback produces the same results
The problem was with the script tag the webpack injects into the index.html
<script type="text/javascript" src="app.06503cbc260646a996d9.js"></script>
The src attribute value was missing a '/' prefix thus the resolution of files failed.
So to make it work, I've linked the src file like this:
<script type="text/javascript" src="/app.06503cbc260646a996d9.js"></script>
As I am using the webpack to bundle js files, on the webpack config I've added output.publicPath '/'
More info: connect-history-api-fallback bugtracker