vue开发中router路由详解

235 阅读2分钟

1.安装

只介绍npm安装
    npm install vue-router --save 项目所需依赖
在main.js或者app.vue中导入
    import Vue from 'vue';
    import VueRouter from 'vue-router';
    Vue.use(VueRouter);
现在就可以开始使用vue-router了

2.结构

先来简单的了解一下使用的结构,方便后面学习
<router-link to="/foo">Go to Foo</router-link> 相当于a标签
<router-view></router-view> 这时用来渲染匹配到的路由组件的
下面就是具体的路由设置了
const app = new Vue({
    router: new VueRouter({
        routes: [{path: '/foo',component: Foo} //匹配到路由'/foo'后渲染组件Foo]
    })
}).$mount("#app")

3.动态路由匹配

说简单点,就是不同的路由值,访问同一个组件
例如:
const router = new VueRouter({
    routes: [
        { path: '/user/:id', component: User }
    ]
})
在 '/user/' 后面跟个 :id 表示这时可选的,就是说不管id是啥,都可以访问User组件
并且这个id存放在this.$route.params中,并且可以有多个这样的可选值
注意点: 在不同的路由值之间切换访问相同的组件,是不会重复渲染的,但是可以通过watch来做出响应
const User = {
    watch: {
        '$route' (to,from) {
        // 对路由变化做出响应
        }
    }
}

4.嵌套路由

嵌套路由很简单,就是匹配到某个路由值,渲染到一个组件,这个组件内部还有router-view,
这时可以传递第二段路由值,加以匹配,如果不传递,可以设置一个空的二段路由值.
例子如下:
const router = new VueRouter({
    routes: [{
        path: '/user/:id',component: User
    }]
})
/user/demo 这个路由值,可以匹配到User组件,如果User组件是如下的
const User = {
    template: `<router-view></router-view>`
}
那么需要对路由配置做如下修改
const router = new Router({
    routes: [
        {
            path: '/user/:id',component: User,
            children: [
                {path: '',component: UserHome},
                {path: 'profile',component: UserProfile}
            ]
        }
    ]
})

5.编程式导航

简而言之,就是,使用js来实现router-link的功能
使用 router.push ,此方法和router-link一模一样,回产生浏览记录,有如下几种形式,和router-link是等价的
router.push('home')
router.push({path: 'home'}) // 和上面等价
router.push({name: 'user',params: {userId: 123}}) // 这个是命名路由,后面讲
router.push({path: 'register',query: {plan: 'private'}}) // '/register?plan=private'

6.命名路由

命名路由是用来给懒人用的,给router-link传递to属性,使用path很长,很难写,所以,起个名字,方便写
当某个路由配置是
const router = new VueRouter({
    routes: [
        {
            path: '/user/:userId',
            name: 'user',
            component: User
        }
    ]
})
正常人是这样访问的 <router-link :to="/user/123"></router-link>
懒人是这样访问的 <router-link :to="{name: 'user',params: {userId: 123}}"></router-link>

7.命名视图

这个玩意儿就是当匹配到一个路由值,同时渲染多个组件,很简单,看下面demo
<router-view></router-view> //这个没有起名的默认就是 default
<router-view name="a"></router-view>
<router-view name="b"></router-view>
const router = new VueRouter({
    routes: [
        {
            path: '/',
            components: {
                default: Foo,
                a: Bar,
                b: Baz
            }
        }
    ]
})
// 这样同时就渲染出 Foo,Bar,Baz 三个组件了

8.重定向和别名

这两个概念也是很简单的
重定向就是当访问一个路由值,定向到另外一个路由值,此即以假乱真,简单demo如下
const router = new VueRouter({
    routes: [{path: '/a',redirect: '/b'}]
})
别名就是起个其它的名字,其实方法的还是这个路由
const router = new VueRouter({
    routes: [{path: '/a',component: A,alias: '/b'}]
})