VueRouter(vue-router 路由)最全笔记,实战实用,通俗易懂

VueRouter

    • 1.安装和使用vue-router
      • 1.1安装
      • 1.2模块化中使用
      • 1.3使用vue-router的步骤
      • 1.4使用history模式
      • 1.5router-link
    • 2.重定向/默认路由
    • 3 点击事件跳转路由
    • 4 动态路由
    • 5 路由懒加载
    • 6 路由嵌套
    • 7 参数传递(一)
    • 8 路由元信息
    • 9 全局导航守卫前置
    • 10 全局后置钩子
    • 11 组件内守卫
    • 12 路由独享的守卫
    • 13 keep-alive

注意
URL:协议://主机:端口/路径?查询(query)

所有的组件都继承自Vue类的原型

打包:npm run build

redirect:[ˌriːdəˈrekt ] 重定向

replace:没有返回箭头

1.安装和使用vue-router

1.1安装

npm install vue-router --save
因为运行到客户端的时候也需要依赖vue-router所以是--save

1.2模块化中使用

src创建router文件夹,里面创建index.js

因为是个插件,所有可以通过Vue.use()来安装路由功能

第一步:导入路由对象,并且==调用Vue.use(VueRouter)==安装插件

第二部:创建路由实例,并且传入路由映射配置

第三部:在Vue实例挂载创建的路由实例

//router/index.js

//配置路由相关信息
import Vue from 'vue'
import VueRouter from 'vue-router'


//1.通过Vue.use(插件),安装插件
Vue.use(VueRouter)

//2.创建 VueRouter对象
const router = [
  
]
const router = new VurRouter({
  // 配置路由和组件之间的应用关系
  router:router,
  mode:history/hash
})

3.将router对象导出传入到vue实例
export default router
//mian.js
import Vue from 'vue'
import App from '/App'
//导入路由 ,index.js可以省略
import router from './router'

Vue.config.productionTip = false

//挂载router
new Vue({
  el:'#app',
  router,
  render: h=> h(App)
})

1.3使用vue-router的步骤

第一步:创建路由组件

第二部:配置路由映射:组件和路径映射关系

第三部:使用路由:通过和

配置映射关系
import Home from '../component/Home'
import About from '../component/About'
const routes = [
  {
    //默认路径
    //重定向
    path:'/',
    redirect:'/home'
  }
  {
    path:'/home',
    component:Home
  },
  {
    path:'/about',
    component:About
  },
  {
    path:'/test',
    component:()=> import ('../component/Test')
  }
]
//App.vue


1.4使用history模式

url的hash
html5的history
const router = new VurRouter({
  // 配置路由和组件之间的应用关系
  router:router,
  mode:'history'
})

1.5router-link

replace :没有返回箭头
<router-link to="/home" replace>首页</router-link>
tag :改变渲染后的标签
<router-link to="/home" tag="button">首页</router-link>
router-link-active:活跃的路由才有的属性
<router-link to="/home" class="router-link-active">首页</router-link>

2.重定向/默认路由

const routes = [
  {
    //默认路径
    //重定向
    path:'/',
    redirect:'/home'
  }
  {
    path:'/home',
    component:Home,
  	meta{
      title:'首页'
    }
  },
  {
    path:'/about',
    component:About
  },
  {
    path:'/test',
    component:()=> import ('../component/Test')
  }
]

3 点击事件跳转路由

method {
  click(){
    this.$router.push('/home')
    this.$router.replace('/home')
  }
}

4 动态路由

(路由传递数据的一种方式)

$route 是当前的活跃路由

params 是 parameters 参数
{
  path:'/user/:id',
  component:User
}

//获取url的id
<div>
  <h2>{{$route.params.id}}
 </div>

<router-link to="/user/12">用户</router-link>
<router-link :to="'/user/'+id">用户</router-link>
data(){
  return {
    id: 34
  }
}

5 路由懒加载

(用到时再加载,不会一进来就和APP.js一起请求回来,一个路由懒加载会单独打包成一个js文件)

推荐 :可以统一管理
const Home = ()=> import('../component/Home.vue')
const routes = [
  {
    path:'/home',
    component:Home
  }
]
或者
const routes = [
  {
    path:'/home'component:()=> import('../component/Home.vue')
  }
]

6 路由嵌套

  1. 创建对应的子组件,并且在路由映射中配置对应的子路由
  2. 在组件内部使用标签
  3. 注意嵌套路由的path不需要加 “/”
const router = [
  {
    path: '/home',
    component: Home,
    children: [
      {
        path:''
        redirect:'news'
      }
      {
        path:'news',
        component:News
      }
    ]
  }
]

//这里的to属性要写全
<router-link to="/home/news"></router-link> 

7 参数传递(一)

注意:parmes 传参只能用name,否则会忽略parmes

传递参数主要有两种类型:params和query

params的类型

  • 配置路由格式:/router/:id
  • 传递的方式:在path后面跟上对应的值
  • 传递后形成的路径:/router/123, /router/abc

query的类型

  • 配置路由格式:/router,也就是普通配置
  • 传递的方式:对象中使用query的key作为传递方式
  • 传递后形成的路径:/router?id=123,/router?id=abc
//query
<router-link :to="{path:'/profile',query:{name:'lihua',age:18}}">我的</router-link>
<div>{{$router.query.name}}</div>

点击事件传参

handleClick(){
  this.$router.push('/profile'+this.userId)
  或者
  this.$router.push({
    path:'/profile',
    query:{
      name:'lihua',
      age:18
    }
  })
}

//params传参跳转   router-link 的 to属性用对象的话必须用name
注意:parmes 传参只能用name,否则会忽略parmes
handleClick(){
  
  或者
  这种写法必须用name
  this.$router.push({
    name:'/profile',
    params:{
      name:'lihua',
      age:18
    }
  })
  parames
}
//这种写法不行用name
<router-link :to="{ name: 'W', params: { id:'1234',age:'12' }}"/>

8 路由元信息

meta:{title:‘lihua’}

注意:获取嵌套路由的信息时,建议:this.$toute.matched[0].meta

const router = [
  {
    path: '/home',
    component: Home,
    meta:{title:'lihua'}
    children: [
      {
        path:''
        redirect:'news'
      }
      {
        path:'news',
        component:News
      }
    ]
  }
]

9 全局导航守卫前置

注意:一定要调用next函数

const router = new VueRouter({ ... })
                              
//router.beforeEach 注册一个全局前置守卫:
注意:一定要调用next函数
router.beforeEach((to, from, next) => {

})
//to:即将前往那个路由
//from:是从那个路由过来的
//next:可
next():直接放行
next(false):中断当前的导航
next('/')或者next({path:'/'})
next(error)


10 全局后置钩子

const router = new VueRouter({ ... })
                              
//router.afterEach 注册一个全局后置守卫:
注意:一定要调用next函数
router.afterEach((to, from) => {

})

11 组件内守卫

在组件内定义即可

  • beforeRouteEnter
  • beforeRouteUpdate
  • beforeRouteLeave
<script>
export default {
data(){
        return{
            name:"Arya"
        }
    },
  beforeRouteEnter(to, from, next) {
    // 在渲染该组件的对应路由被 confirm 前调用
    // 不!能!获取组件实例 `this`
    // 因为当守卫执行前,组件实例还没被创建
  },
  beforeRouteUpdate(to, from, next) {
    // 在当前路由改变,但是该组件被复用时调用
    // 举例来说,对于一个带有动态参数的路径 /foo/:id,在 /foo/1 和 /foo/2 之间跳转的时候,
    // 由于会渲染同样的 Foo 组件,因此组件实例会被复用。而这个钩子就会在这个情况下被调用。
    // 可以访问组件实例 `this`
  },
  beforeRouteLeave(to, from, next) {
    // 导航离开该组件的对应路由时调用
    // 可以访问组件实例 `this`
  }
}
</script>

12 路由独享的守卫

在路由配置上直接定义 beforeEnter 守卫:

const router = new VueRouter({
  routes: [
    {
      path: '/foo',
      component: Foo,
      beforeEnter: (to, from, next) => {
        // ...
      }
    }
  ]
})

13 keep-alive

keep-alive是Vue内置的一个组件,可以使包含的组价保留状态,或避免重新渲染。

  • 有两个非常重要的属性:
  • include-字符串或正则表达式,只有匹配的组件会被缓存
  • exclude-字符串或正则表达式,只有匹配的组件不会被缓存

router-view也是一个组件,如果直接被包在keep-alve里面,所有路径匹配到的视图组件都会别缓存

//多个名称要用逗号分开,不能有空格
这两个组件会被缓存
<keep-alive inclued="Profile,News">
  <router-view />
</keep-alive>

export default {
  name:'Profile'
  data(){
    return {
      
    }
  }
}
export default {
  name:'News'
  data(){
    return {
      
    }
  }
}
本文是将我学过的VueRouter笔试重点的知识进行归纳总结,如果你认为写的不错的话,求点赞,求收藏,感谢!!!

你可能感兴趣的:(Vue,vue.js,前端,javascript)