VueRouter 的原理及自定义Route

Vue Router 实现原理

  • Vue Router基础
  • Hash模式 和 history模式
  • 模拟实现自己的Vue Router

基本使用
在使用vue创建项目时,使用Rouer选项自动安装依赖项

import Vue from 'vue'
import VueRouter from 'vue-router'
import Index from '../views/Index.vue'
// 1. 注册路由插件
Vue.use(VueRouter)

// 路由规则
const routes = [
  {
   
    path: '/',
    name: 'Index',
    component: Index
  },
  {
   
    path: '/blog',
    name: 'Blog',
    // route level code-splitting
    // this generates a separate chunk (about.[hash].js) for this route
    // which is lazy-loaded when the route is visited.
    component: () => import(/* webpackChunkName: "blog" */ '../views/Blog.vue')
  },
  {
   
    path: '/photo',
    name: 'Photo',
    // route level code-splitting
    // this generates a separate chunk (about.[hash].js) for this route
    // which is lazy-loaded when the route is visited.
    component: () => import(/* webpackChunkName: "photo" */ '../views/Photo.vue')
  }
]
// 2. 创建 router 对象
const router = new VueRouter({
   
  routes
})

export default router

挂载到节点

import Vue from 'vue'
import App from './App.vue'
import router from './router'

Vue.config.productionTip = false

new Vue({
   
  // 3. 注册 router 对象
  router,
  render: h => h(App)
}).$mount('#app')

使用vue router

<template>
  <div id="app">
    <div>
      <img src="@/assets/logo.png" alt="">
    </div>
    <div id="nav">
      <!-- 5. 创建链接 -->
      <router-link to="/">Index</router-link> |
      <router-link to="/blog">Blog</router-link> |
      <router-link to="/photo">Photo</router-link>
    </div>
    <!-- 4. 创建路由组建的占位 -->
    <router-view/>
  </div>
</template>

<style>
#app {
   
  font-family: Avenir, Helvetica, Arial, sans-serif;
  -webkit-font-smoothing: antialiased;
  -moz-osx-font-smoothing: grayscale;
  text-align: center;
  color: #2c3e50;
}

#nav {
   
  padding: 30px;
}

#nav a {
   
  font-weight: bold;
  color: #2c3e50;
}

#nav a.router-link-exact-active {
   
  color: #42b983;
}
</style>

使用vue router时

会给Vue实例挂载 r o u t e , route, route,router 两个属性
route 存储了当前的路由规则,当前路由的规则
router 存储了VueRouter对象,路由对象中提供了一些路由的方法,还有一些路由信息,mode当前模式,存储在_proto_,像是一些push,go,back等方法

动态路由
动态路由指路由传参

const routes = [
  {
   
    path: '/',
    name: 'Index',
    component: Index
  },
  {
   
    path: '/detail/:id',
    name: 'Detail',
    props: true,
    component: () 
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值