Vue路由初体验

204 阅读3分钟

1. Vue路由详解

/* 导入Vue构造函数 */
import Vue from 'vue'
/* 导入VueRouter构造函数 */
import VueRouter from 'vue-router'
/* 导入HomeView页面 */
import HomeView from '../views/HomeView.vue'
/* 调用构造函数Vue的use方法 传入VueRouter构造函数 
作用是:把VueRouter当作一个插件 全局插入到Vue中*/
Vue.use(VueRouter)
/* 定义一个路由数组对象 */
const routes = [
  /* 一个对象就对应了一个路由
  path就是路由的地址
  name给路由起个名字
  component就是具体跳转的页面
  */
  {
    /* path: '/' 表示根路径 一进入页面跳转的组件 */
    path: '/',
    name: 'home',
    /* 这种方式一进入页面就会全部加载,不是用到的时候再加载
    性能没有懒加载方式好 */
    component: HomeView,
    /* 可以使用redirect重定向 一进入主页就展示第一个子页面
    redirect后面跟的是路径名 */
    /* 因为/是根路径 所以可以直接写one */
    redirect:'/one',
    children:[{
      path:'one',
      name:'one',
      component: () => import('../views/OneView.vue')
    }]
  },
  {
    /* 这里是一级目录所以可以加/ /表示根目录 */
    path: '/about',
    name: 'about',
    /* 懒加载 一开始的时候不加载 当你切换的这个路由的时候再加载 */
    component: () => import('../views/AboutView.vue'),
    /* about不是根路径 所以redirect后面的路径要写全/about/aboutchild */
    redirect:'/about/aboutchild',
    // ★ 子路径不需要加/
    children:[{
      path:'aboutchild',
      name:'aboutchild',
      component: () => import('../views/AboutChild.vue'),
    }]
  },
  {
    path: '/childa',
    name: 'childa',
    /* 懒加载 一开始的时候不加载 当你切换的这个路由的时候再加载 */
    component: () => import('../views/ChildA.vue')
  },
  {
    path: '/childb',
    name: 'childb',
    /* 懒加载 一开始的时候不加载 当你切换的这个路由的时候再加载 */
    component: () => import('../views/ChildB.vue')
  },
  {
    /* path: '*'按照常理要放在最后 ★ */
    /* path: '*' 表示上面的路由没有匹配到 则进入下面的页面 */
    path: '*',
    name: 'notfound',
    /* 懒加载 一开始的时候不加载 当你切换的这个路由的时候再加载 */
    component: () => import('../views/NotFound.vue')
  },
  
]

/* 实例化构造函数VueRouter 产生一个实例化对象router 
并把上面的路由数组对象routes当作参数 以对象的方式传给构造函数VueRouter*/
const router = new VueRouter({
  routes:routes
})

/* 把实例化路由对象router默认导出 */
export default router

路由的使用

<template>
  <div id="app">
    <nav>
      <!-- router-link组件是负责跳转的 to属性是用来写跳转的路径 
      router-link组件本质上是由a标签来实现的 路由跳转的原理是根据锚点来的
       -->
      <router-link to="/">Home</router-link> |
      <router-link to="/about">About</router-link> |
      <router-link to="/childa">ChildA</router-link> |
      <router-link to="/childb">ChildB</router-link>
    </nav>
    <!-- router-view组件是用来展示组件的容器 -->
    <router-view/>
  </div>
</template>

2. Vue路由的传参

客户点击页面触发服务器路由设置好的值,页面通过路由对应的值渲染不同的画面

静态传参:在跳转属性直接传值,跳转页通过$requery查询传来的值
动态传参:首先在路由配置文件index开启`props:ture`,再对路由的路径添加动态的内容/:id。
最后在页面跳转属性后添加“/+动态的值”,用添加props:['']接受值,可以通过this.获取。
proprs还可以通过this.$route.params进行获取。 
<template>
  <div id="app">
    <nav>
      <router-link to="/">Home</router-link> |
      <router-link to="/about">About</router-link> |
      <router-link to="/childa?name=laozhang">ChildA</router-link> |
      <router-link to="/childa?name=laowang">ChildA</router-link> |
      <router-link to="/childb/1">ChildB</router-link> |
      <button @click="click">跳转到ChildA</button>
      <button @click="addroute">添加路由</button>
    </nav>
    <router-view/>
  </div>
</template

# ChildA
<template>
  <div>
      <h1>我是A</h1>
      <h2>{{shuchumsg}}</h2>
      <h2>{{msg}}</h2>
      <button @click="click">backhome</button>
  </div>
</template>

<script>
export default {
//静态接受
    watch:{
      $route:{
        deep:true,
        // handler 操作
        handler:function(){
          let name = this.$ .query.name
           if(name =='laozhang'){
              this.msg = "欢迎老张"
            }else if(name == 'laowang'){
              this.msg = "欢迎老王"
            }else{
               this.msg = "欢迎xx"
            }
        },
        immediate:true
      }
    },
    computed:{
        shuchumsg(){
            let name = this.$route.query.name
            if(name =='laozhang'){
               return '老张来了'
            }else if(name == 'laowang'){
                return '欢迎老王'
            }else{
               return '欢迎xx'
            }
        }
    }
}
//动态接受
<script>
export default {
   data(){
        return {
            msg:""
        }
    },
    props:['id'],
    created(){
      if(this.id == '1'){
              this.msg = "用户选取了1"
            }else if(this.id == '2'){
              this.msg = "用户选取了1"
            }else{
               this.msg = "用户啥都没选"
            }
    }
}
</script>

3. Vue路由的添加

 addR(){
      this.$router.addRoute({
        path: '/vip',
        name: 'vip',
        /* 路径使用@表示src的方式实现 */
        /* 或者在本页面 使用./views/VipView.vue 的方式 获取页面*/
        component: () => import('@/views/VipView.vue')
      })
      console.log(this.$router)
    },
    /* 给about加上子路由 */
    addR2(){
      /* ★添加子路由的时候需要第一个参数是主路由的name值 */
      this.$router.addRoute('about',{
        path:'aboutchild2',
        name:'aboutchild2',
        component: () => import('@/views/AboutChild2.vue'),
      })
      /* this.$router.currentRout表示当前所在的路由 */
      console.log(this.$router.currentRoute)
    }
  }

4. Vue路由的跳转

通过点击事件触发,跳转配置

// 直接写路径
 click(){
      this.$router.push('/childa')
    },
// 传对象{name:''}   
  click(){
      this.$router.push({name:'childa'})
    },

5. Vue路由的钩子函数

全局跳转前/后的钩子

所有路由相互跳转都会触发。

export default {
  created(){
    this.$router.beforeEach((to,from,next)=>{
      console.log('to',to);
      console.log('from',from);
      next()
    })
    //不用next()
    this.$router.afterEach((to,from)=>{
      console.log('to',to);
      console.log('from',from);
    })
  },

局部跳转前/后函数

 1 指定某路由跳转前后触发,其他路由相互跳转无效
 2 在同一路径的路由相互跳转(如:同路径动静态传参路由)也没有作用,
   因为同属于一个钩子函数下。★
// #router/index
  {
    path: '/childa',
    name: 'childa',
    component: () => import( '../views/ChildA.vue'),
    beforeEnter:(from,to,next)=>{
      console.log(from);
      console.log(to);
      next()
    }
  },