1. vue anso vue-router
npm install -save vue-router
//package文件的dependencies节点写入依赖 dependencies部署是需要的 depenDencies 开发依赖,部署时不需要
2. vue references vue-router
and creates the router folder under the src directory.
Create the index.js file under the router folder.
index.js
import Vue from 'vue'
import Router from 'vue-router'
Vue.use(Router);
export default new Router({
routes: [
{
path: '/',
name: 'login',
component: Login
},
{
path: '*',
name: '404',
component: E404
},
{
path: '/404',
name: '404',
component: E404
},
],
});
Introduce index.js into main.js
import router from './router/index';
let vue = new Vue({
el: '#app',
router,
store,
components: { App },
template: '<App/>'
});
3. Router configuration
Nested routing, be careful not to start the sub-route with "/"
{
path: '/component',
name: 'component',
meta: {
requireAuth: true // 判断是否需要登录
},
component: Component,
children: [
{
path: 'view',
component: MyComponent
},
{
path: 'upload',
component: UploadComponent
},
{
path: 'setting',
component: SetComponent
},
{
path: 'update',
component: UpdateComponent
}
]
},
4. Use of routing
路由跳转
this.$router.push("");
监听路由变化
watch: {
$route(to , from){
let path = to.path;
if(path.lastIndexOf("/") > 0){
path = path.substring(path.lastIndexOf("/")+1);
}
this.active = path;
}
}
For other information, please refer to the API documentation.
5. The difference between $router and $route:
$router is a global routing object, which can be used for routing jumps, etc.
$route is the object of the current route, which can be used to obtain the address, parameters, etc. of the current route.