Vue-Router基础使用

作为Vue生态系统里面的一大成员,Vue-Router主要负责vue中的页面路由及其传值问题。

1、基本使用–添加路由

基本使用主要包括四个部分,页面引入、配置路由数组、实例化路由、把实例化的路由加入Vue的实例化中。如下,

// 组件引入,主要有以下三种方式
const index = resolve => require(['./index'], resolve) // 组件异步引入,不会打包到webpack的main.js里面
import Bar from '../bar'                               // 组件同步引入,会打包到webpack的main.js里面
const Foo = { template: '<div>foo</div>' }             // 组件同步引入,会打包到webpack的main.js里面
// 配置路由数组--路由真正的详细配置
const routes = [ 
    { path: '/index', component: index}, 
    { path: '/foo', component: Foo},
    { path: '/bar', component: Bar}
]
// 实例化路由
const router = new VueRouter({
mode: 'history', // 两种类型history 还有 hash routes: routes // 可以缩写成routes }) // 在Vue实例化中加入路由实例 new Vue({ el: '#app', router, render: h => h(App) })

四步完成后,路由信息就添加到整个Vue实例中,可供全局调用了。

而在路由的详细配置中,还有很多信息,下面看一个相对详细点的,

const routes = [{
    path: '/pages/trade',
    component: App,
    children: [{
        path: '/',
        component: index,
        name: 'index',
        meta: {
            title: '导航页'
        }
    }, {
        path: 'confirm',
        component: confirm,
        name: 'confirm',
        meta: {
            title: '确认订单'
        },
        children: addressRouter
    }]
}, {
    path: '/pages/sale',
    component: App,
    children: [{
        path: 'product/:productId(\\d+)',
        component: product,
        name: 'product',
        meta: {
            title: '商品详情'
        }
    }]
}, {
    path: '*',
    component: noFound,
    name: 'err',
    meta: {
        title: '404'
    }
}]

路由中主要涉及到的一些参数

ItemValue
name路由标识
path路由标识,路由路径
component实际组件
children: 子路由
meta: 附加信息,可以包含一些诸如title的信息

name和path很相似,都可以用来作为跳转的标识,但有以下几点不同

1) path最终会作为url的一部分,name不会。

2) path里面可以做一些正则匹配,而name里面一般不会添加正则来做更多的匹配。

2、声明式路由与编程式路由 – 路由基本使用

引入路由之后,vue-Router的使用也十分方便。主要由以下两种方式

// 声明式路由
<router-link class="common_ques" :to="{ name: 'foo', params: { productId: 123 }}">Foo</router-link>
<router-link class="common_ques" :to="{ path: 'foo', query: { productId: 123 }}">Foo</router-link>
// 编程式路由
router.push({
name: 'foo',
params: {
     a: 'a'
     }
})

两种方式一个用于template中,一个用于script中,跳转效果一致, 但相比而言router.push的形式灵活性更好一些。就像下面两个一样

<a href="www.baidu.com"></a>

window.location.href = 'www.baidu.com'

下面以编程式路由详细说一下

// 编程式路由
router.push({
name: 'foo',
params: {
     a: 'a'
     }
})

编程式路由主要有push、replace、go三中方法。

1)push、replace

这两种方法主要接受两类参数,

·路径:name/path

·参数:params/query

name和path的区别上文已经提过。params和query两个都是用来进行路由参数传递的,不同的是query传递的参数会以出现在url中的search部分,而params的则不会,其他基本一致。params和query可以同时传递,但一般没啥必要。。。

2)go

go只接收一个参数,就是数字~~。和history的go是一样的,自行领会。

参数的接收和使用

上面说了传参,下面看看怎么接收和使用,很简单

this.$route.query
this.$route.params

刚开始用的时候,注意别写成router就好了。

下一部分再写一下关于钩子的使用、路由模式一些问题,这次到这吧。