When to use <router-link> vs <a>
<router-link>
is intended for in-app links (e.g., to a page within your app). Use <a>
for external links.
‘vue-router’ is a separate package to Vue and is installed by ‘webpack’.
Routes are set up in router/index.js
Import to Router from vue-router which is in node_modules.
import Router from 'vue-router'
... new Router...
creates an instance of Router which is an object with a property ‘routes’ which is an array of object. Each of those objects is a route with properties for ‘path’, ‘name’ which is what it is called and ‘component’, the component that is called when the route is used.
{
path: '/about',
name: 'About',
component: About
}
We need to import the component and we use the @ which brings the path to the root of the project which is the ‘src’ directory.
import About from '@/components/About'
The component gets loaded into the root component App.vue using,
<router-view/>
and where that tag is in the App.vue. This would allow us to place a navbar, header and footer for example around this About component. So that when you go to …/about only the about component in the page changes and the whole page doesn’t refresh.
Next create a NavBar component and place it in the App.vue template.
This will work,
<a href="/about">About</a>
however in vue it should be done like this,
<router-link to="/about>About</router-link>
When <router-link> is rendered to the browser it becomes <a> so in the css we still reference it as ‘a’ not as ‘router-link’.
We can data bind using the ‘to’ attribute in <router-link>like this,
:to={ name: 'About'}
where ‘name’ is the property in the ‘routes’ array of object in the main.js routes. This makes the route dynamic.
Using this data bind to change to ‘/about’ to something else such as ‘abt’ you only need to change,
path: 'abt',
in the routes array of objects.
Router link : if we use router link the page will not reload but with <a>
link the navigation occured through page refresh.