加载方式

  1. npm install vue-router
    1. import Vue from ‘vue’
    2. import VueRouter from ‘vue-router’
    3. Vue.use(VueRouter)
  • HTML
    • 热点名字
    • 路由匹配到的组件渲染到这里
  • JavaScript

    • 基础
      • const Foo = { template:’
        foo
        ‘ }
      • const routes = [ { path:’路由’,component:Foo } ]
      • const router = new VueRouter({ routers })
      • const app = new Vue({ router }).$mount(‘#app’)

        动态路由完全匹配 定义越早 优先级越高

  • $route.params

    • routers = [{ path:’/路由/:key’,compent:组件 }] —key可以是任意值,用$route.params.key获取
    • 原来的组件会复用,组件内的生命周期不会再调用,解决方法:
      • 可用watch监听$route对象,来更新data (watch方法写在组件内无效)
        • watch: {“$route”: function(){ … } }
      • 用 :key 来阻止“复用”:
        • computed: { key() { return this.$route.name !== undefined? this.$route.name +new Date(): this.$route +new Date() } }
      • 通过vue-router的钩子函数 beforeRouteEnter | beforeRouteUpdate | beforeRouteLeave
        • beforeRouteUpdate(to,from,next){ … next(); }
  • 捕获所有路由 *
    • path: ‘*’
    • path: ‘/user-*’
      • $route.params会自动添加一个pathMath参数 包含*部分

        嵌套路由 被渲染的组件中还可以包含自己的嵌套router-view

        image.png

        编程式导航

        ```javascript // 命名的路由 router.push({ name: ‘user’, params: { userId: ‘123’ }})

// 带查询参数,变成 /register?plan=private router.push({ path: ‘register’, query: { plan: ‘private’ }}) ``` 如果提供了path,params会被忽略

  • router.replace(…) 不会添加新记录
  • router.history.go(n) 类似window.history.go(n)

History

需要后端配置:

  • nginx
    • location / { try_files $uri $uri/ /index.html; }
  • nodeJs

懒加载
讲异步组件定义为返回一个Promise的工厂函数,其他没什么不同
const foo = ()=>{
Promise.resolve({ … })
}