02-vue-router

87 阅读1分钟

vue-router 动态路由

两种方式,

一种 $route.params.id 获取值

一种 路由中设置 props 为 true , 在子组件中设置props:['id'], 直接取 id 的值即可。

<template>
  <div class="about">
    <!--方式一: 通过路由规则获取参数 -->
    <h3>{{ $route.params.id }}</h3>
    <h1>This is an about page</h1>
    <!--方式二: 通过设置 Props 获取参数 -->
    <h2>{{ id }}</h2>
  </div>
</template>
<script>
export default {
  props:['id'],
  setup() {
    
  },
}
</script>

hash 模式和 history 模式的区别

hash 模式是基于 锚点以及, 以及 onhashchange 来实现的

  • URL 中#后面的内容作为路径地址
  • 监听 hashchange 事件
  • 根据当前路由地址找到对应组件重新渲染

history 模式是基于 HTML5 中的 history API

history.pushState() IE10 之后才支持 history.replaceState

  • 通过 history.pushState()方法改变地址栏

  • 监听 popstate 事件

  • 根据当前路由地址找到对应组件重新渲染

history 模式使用

  1. history 模式需要配合服务器的支持
  2. 单页应用中,服务端不存在 www.testurl.com/login 这样的地址会返回找不到该页面
  3. 在服务端应该除了静态资源外都返回单页应用的 index.html

在 node 服务器中,history 模式需要使用中间件(connect-history-api-fallback),

在 nginx 服务器中,增加 try_file $uri

server { 
location / { 
    root html;
    index index.html index.htm;
    try_file $uri
 }
}

vue-router 实现原理

Vue 前置只是

  • 插件
  • 混入
  • Vue.observable()
  • 插槽
  • render 函数
  • 运行时和完整版的 Vue

Vue 的构建版本

  • 运行时版: 不支持 template 模板, 需要打包的时候提前编译
  • 完整版: 包含运行时和编译器, 体积比运行版本大10K左右,程序运行的时候把模板转换成 render 函数

runtimeCompiler

  • 是否使用包含运行时编译器的 Vue 构建版本, 设置为 true 后你就可以在 Vue 组件中使用 template 选项了, 但是这会让你的应用额外增加 10KB