vue-router

vue-router

官方文档:

旧版:https://github.com/vuejs/vue-router/tree/1.0/docs/zh-cn

新版:http://router.vuejs.org/(2.0版本)

此文是旧版

vue-router_第1张图片

基本用法:

是一个顶级的路由外链,用于渲染匹配的组件。

例如:我的应用入口是app.vue

那么在app.vue中添加如下代码, 此处涉及ES6,可以先看下这篇文章:http://www.csdn.net/article/2015-04-30/2824595-Modules-in-ES6

app.vue



Footer是一个公用的页脚组件,存放于components文件夹中

footer.vue



由于app.vue是最顶级的入口文件,在app.vue中引用footer组件的话,所有页面都会包含footer内容,但是二级页面等子页面不需要,所以得把app.vue中代码复制到index.vue中,把app.vue中footer相关的部分删掉。

在index.html中添加如下代码,创建一个路由实例。

<app>app>

在main.js中配置route.map

main.js

import Vue from 'vue'
import VueRouter from 'vue-router'//导入vue-router
//导入组件
import App from './App'
import Index from './page/index'
import list from './page/list'
import Home from './page/home'
import Account from './page/account'
Vue.use(VueRouter)
var router = new VueRouter()
router.map({
    //默认指向index
    '/':{
        name:'index',
        component:Index,
        //子路由(有页底)
        subRoutes:{
            '/home':{
                name:'home',
                component:Home
            },
            '/account':{
                name:'account',
                component:Account
            }
        }
    },
    //没有footer
    '/list':{
        name:'list',
        component:list
    }
})
//启动一个启用了路由的应用
router.start(App,'app')

router.start中的'app',指的是index中的:,可以取其他的名字,但是得和index中的名字一致。

这时启动项目(npm run dev)会发现,页面上只有footer,而没有显示其他内容。因为index.vue本来就只有footer而没有其他内容,但是我们肯定要显示页面,就要用到

router.redirect(redirectMap)重定向

例如:我们要默认载入home页面

在main.js中加入

//重定向到home
router.redirect({
    '*':'home'
})
router.start(App,'app')
 在index中加入init()函数

然而,经过测试,redirect并没有重定向的home,载入home的真正原因是:router.go('/home')

此时,进入项目就会显示home页面的内容了。

vue-router_第2张图片

路由规则和路由匹配

Vue-router 做路径匹配时支持动态片段、全匹配片段以及查询参数(片段指的是 URL 中的一部分)。对于解析过的路由,这些信息都可以通过路由上下文对象(从现在起,我们会称其为路由对象)访问。 在使用了 vue-router 的应用中,路由对象会被注入每个组件中,赋值为 this.$route ,并且当路由切换时,路由对象会被更新。

$route.path

字符串,等于当前路由对象的路径,会被解析为绝对路径,例如:/list,来源于route.map中配置的路径

router.map({
   '/home':{
    name:'list',
    component:Home
    } 
})

dom中

<a v-link="{path:'/list'}">前往list列表页面a>
或者(具名路径)

<a v-link="{name:'list'}">前往list列表页面a>
带参数跳转(例如:从列表页跳转到列表详情页)

<ul>
    <li v-for="item in alllist">
        
        <a v-link="{ name: 'listDetail',params:{id: item.id }}">
            {{item.title}}
        a>
    li>
ul>
Promise & ES6 详见vue-router的data部分: http://router.vuejs.org/zh-cn/pipeline/data.html


详情页代码


   

{{listDetail.title}}


   

阅读:{{listDetail.viewTimes}}发布时间: {{listDetail.publishTime | timer}}


   

       {{{listDetail.content}}}
   



此时router要做下修改

'/list':{
    name:'list',
    component:GetReceipt
},
'/listDetail/:id':{
    name:'listDetail',
    component:GetReceiptDetail
}

转载地址http://www.cnblogs.com/jyichen/p/5660865.html

你可能感兴趣的:(vue-router)