加载方式
- npm install vue-router
- import Vue from ‘vue’
- import VueRouter from ‘vue-router’
- Vue.use(VueRouter)
- HTML
热点名字 路由匹配到的组件渲染到这里
JavaScript
$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(); }
- 可用watch监听$route对象,来更新data (watch方法写在组件内无效)
- 捕获所有路由 *
// 带查询参数,变成 /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({ … })
}
