Vue Router详解,Vue Router钩子函数详解

想必来查看笔者的这篇Vue Router文章的人,应该了解什么是Vue Router,至少知道其的作用是路由映射,所以笔者在这里不再赘述。
假设我们现在有一些简单的vue组件,
MyHeader.vue:

<template>
  <div class="container">
    this is header of each page
  </div>
</template>

<script>
export default {
   
  name: "my-header"
}
</script>

index.vue

<template>
  <div>
    <div class="container">this is home page</div>
  </div>
</template>

<script>
export default {
   
  name: "index"
}
</script>

second.vue:

<template>
  <div>
    <div class="container">this is second page</div>
    <span>{
   {
   id}}</span>
  </div>
</template>

<script>
export default {
   
  name: "second"
}
</script>

这三个组件中的container样式一样:

<style lang="scss" scoped>
.container{
   
  border: #bfbfbf 1px solid;
  width: 200px;
  height: 100px;  
  margin:10px 0;
}
</style>

1. 构建基本的router

我们希望我们的单页面由my-header和一个index / second组件组成,页面中展示 index / second 需要使用router来解决。
router.js

import Vue from 'vue'
import VueRouter from 'vue-router'

import index from "../view/index"
import second from "../view/second"

Vue.use(VueRouter)

const routes = [
  {
   
    path: '/',
    redirect: '/home'
  },
  {
   
    path:'/home',
    name: 'home',
    component: index,
  },{
   
    path:'/second',
    name: 'second',
    component: second,
  }
]

let router = new VueRouter({
   
    mode: 'history',
    routes
}

export default router

这就是一个简单的router,当我们导航到指定路径时,<router-view/> 标签就会被相应的component组件替换。
我们这里在router.js直接引入了组件,为了提高带宽利用率,提高性能,我们使用动态引入的方式来加载模块:

//import second from "../view/second"
//component: second
component: () => import('../view/second') 

注意:如果使用了异步加载组件的方式,我们需要使用@babel对此语法进行解析:

npm install --save-dev @babel/plugin-syntax-dynamic-import

修改babel配置:

{
   
  "plugins": ["@babel/plugin-syntax-dynamic-import"]
}

为了方便路由切换,我们在my-header组件中增加两个router-link:

<template>
  <div class="con
  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值