vue-router

173 阅读1分钟

基础使用

  • 安装
  • 使用

router.js

import Vue from 'vue';
import VueRouter from 'vue-router';

Vue.use(VueRouter);
const router = new VueRouter({
    mode: 'history | hash(默认)',
    //=>HASH ROUTER 和 BROWSER ROUTER
    routes: [...]
});

export default router;

main.js

import Vue from 'vue';
import router from './router';

Vue.config.productionTip = false;
new Vue({
  router, 
  //=>this.$router 包含路由跳转的方法
  //=>this.$route 包含路由的基本信息
  render: h => h(App)
}).$mount('#app');

一级路由和二级路由

const router = new Router({
    mode:'xxx',
    //=>一级路由
    routes:[{
        path:'/', //=>路由路径(后期跳转和匹配的时候需要,例如:<router-link to='/'> 或者 :to='{path:'/'}'name:'xxx', //=>命名路由(后期可基于 <router-link :to='{name:'xxx'}'> 跳转)
        props:true, //=>如果有动态路由传递参数,直接把参数信息当做属性传递给组件,例如:path:'/list/:type/:id',组件中就可以基于 props:['type','id'] 获取传参到的信息,跳转的时候可以 this.$router.push('/list/teacher/1000') 跳转和传递信息,当然不这样处理,也可以基于 this.$router.params 来获取传递的参数
        component:xxx, //=>渲染的组件
        //component:_=>{
            //return import('xxx'); //=>返回的是一个promise实例(内部保存了解析并编译xxx.vue后得到的一个模块)      
        //},
        //component:{
            //=>也可以是一个对象,项目中可能会出现两个<router-view>同时使用,此时给其设置name='xxx',这样在路由表中就可以基于不同的名字来渲染多个组件了
            //default:xxx,
            //view2:xxx
        //}
    },{
        path:'/home',
        component:xxx,
        //=>二级路由
        children:[{
            path:'',
            //=>路由重定向
            //redirect:'/home/list',
            redirect:{
                path:'/home/list',
                params:{xxx:xxx}, //=>可传递参数信息
            }
        }...]  
    },{
        //=>404页面处理,也可以重定向
        path:'*',
        component:ErrorComponent
    }]
});

构建路由视图容器(命名视图)

<router-view></router-view>
<router-view name='view2'></router-view>

实现路由跳转和传参(编程式导航)

<router-link to='/xxx'></router-link>
//=>传递参数
<router-link :to='{name:'xxx',params:{xxx:xxx}}'></router-link>

/*编程式导航:JS中实现跳转*/
this.$router.push('/xxx');
this.$router.push({name:'xxx',params:{id:100}}); //=>/xxx/100
this.$router.push({path:'/xxx/100'});
this.$router.push({path:'/xxx',query:{id:100}});//=>/xxx?id=100 获取this.$router.query.id
this.$router.go(-1);

动态路由

export default new Router({
    routes:[{
        path:'/xxx/:n/:m'
    }]
})

this.$router.push('/xxx/100/200');

组件复用,基于watch监听$route