vue基础教程(四) - 路由的配置、跳转、传参、嵌套

说明:本篇主要讲述VueRouter。(会配上核心代码片段,本篇讲述的内容核心已在我的个人博客项目中实现)

https: https://github.com/shulongfei/vue-blog-pro.git

下载方式1):git clone https://github.com/shulongfei/vue-blog-pro.git

下载方式2):https://github.com/shulongfei/vue-blog-pro.git

github上面代码目前有点问题,明天测试之后重传(2018-8-8)尴尬。-内容可以正常看

一、通过VueRouter来实现一个SPA的基本步骤:

①引入对应的vue-router.j
②指定一个盛放代码片段的容器
<router-view></router-view>
③创建业务所需要的各个组件
④配置路由词典
    每一个路由地址的配置对象(要加载哪个页面...)
    const myRoutes = [
        {path:'/myLogin',component:TestLogin},
        {path:'/myRegister',component:TestRegister}
    ]
    const myRouter =  new VueRouter({
        routes:myRoutes    
    })
    new Vue({
        router:myRouter    
    })
⑤测试
    在地址栏中 输入对应的不同的路由地址 确认是否能够加载对应的组件

基于脚手架路由完整配置事例(博客中有):

import Vue from 'vue'
import Router from 'vue-router'
import VueResource from 'vue-resource'

import Main from '@/components/Main'
import Index from '@/components/Index'
import header from '@/components/include/header'

Vue.use(Router)
Vue.use(VueResource)

export default new Router({
  routes: [
    {
      path: '/',
      name: 'index',
      component: Index
    },
    {
      path:'/header',
      component:header,
      children:[
        {
          path:'/main',
          component:Main
        }
      ]
    }
  ]
})

二、通过VueRouter来实现组件之间的跳转
提供了3种方式实现跳转:
①直接修改地址栏中的路由地址

②通过router-link实现跳转
<router-link to="/myRegister">注册</router-link>

③通过js的编程的方式
 jumpToLogin: function () {
     this.$router.push('/myLogin');
 }

从首页跳转到博客主页面的事例:

<template>
  <div>

    <div class="container-fuild">
      <div class="img"></div>
      <div class="content">
        <div class="title">逆水行舟,不进则退!</div>
        <div class="description">最糟糕的是人们在生活中经常受到错误志向的阻碍而不自知,真到摆脱了那些阻碍时才能明白过来。</div>
        <div class="time">—— 2018.08.08 ——</div>
        <div class="btn">
          <router-link to="/main">进入博客</router-link>
        </div>
      </div>
    </div>

  </div>
</template>

<script>
  export default{
    data:function(){
      return {
        msg:'Hello Index'
      }
    }
  }
</script>

<style></style>

三、通过VueRouter来实现组件之间的跳转:参数的传递

①明确发送方和接收方
②配置接收方的路由地址
  

{path:'/myTest',component:TestComponent}
{path:'/myTest/:id',component:TestComponent}


③接收方获取传递来的数据
    this.$route.params.id
④跳转的时候,发送参数

this.$router.push('/myTest/20')
<router-link :to="'/myTest'+id">跳转</router-link>

方法比较简单就暂时不做说明了,小的例子需要请留邮箱(全套发送)。

四、路由设置高级用法

alias 别名
    {path:'/list',component:MyList,alias:'/lists'}

redirect 重定向
    {path:'/productList',redirect:'/list'}

path:'*' 异常处理
    {path:'*',component:'NotFound'}

五、路由嵌套(个人认为比较核心的东西)
①准备嵌套其它组价的父组件 指定一个容器
在A组件指定一个容器
<router-view></router-ivew>

②在A组件的路由配置对象中指定children属性
 

{ 
    path:'/a',
    component:A,
    children:[
      {path:'/b',component:B},
      {path:'/c',component:C},
    ]
}

博客内容有该例子,请参考,如有疑问请联系博主,共同学习,共同进步。

转载请注明出处,谢谢!!!!!!!!

猜你喜欢

转载自blog.csdn.net/weixin_42457316/article/details/81511208
今日推荐