认识懒加载
- 路由中通常会定义很多不同的页面,这些页面通常情况下会被打包到一个js文件中,如果我们一次性请求完这些页面,可能会花费一定的时间,甚至用户的电脑都可能会出现短暂的白屏,为了避免这种情况,就必须使用路由懒加载
- 路由懒加载的作用就是路由对应的组件会被打包成一个个js代码,只有在这个路由被访问到时,才加载对应的组件
懒加载的使用效果
懒加载的使用方式
import Home from '../components/Home.vue'
import About from '../components/About.vue'
import User from '../components/User.vue'
Vue.use(VueRouter)
const routes = [{
path: '',
redirect: '/home'
},
{
path: '/home',
component: Home
},
{
path: '/about',
component: About
},
{
path: '/user/:user_id',
component: User
}
]
- 使用懒加载后
- 通过import()方法导入需要的组件,然后使用变量将需要的组件保存起来
const Home = () => import('../components/Home.vue')
const About = () => import('../components/About.vue')
const User = () => import('../components/User.vue')
Vue.use(VueRouter)
const routes = [{
path: '',
redirect: '/home'
},
{
path: '/home',
component: Home
},
{
path: '/about',
component: About
},
{
path: '/user/:user_id',
component: User
}
]
认识路由嵌套
- 路由嵌套是一个很常见的功能,比如在Home页面,我们希望通过/Home/News或/Home/Message访问一些内容。一个路径映射一个组件,访问这两个路径也会分别映射两个组件
路由嵌套的使用
- 在对应的路由配置对象里面配置子路由
- 在父组件内部使用
<router-view>
{
path: '/home',
component: Home,
//通过children属性,在home组件中添加两个子组件映射关系
children: [{
path: '/home',
redirect:'/home/news'
},
{
path: 'news',
component: HomeNews
},
{
path: 'message',
component: HomeMessage
}
]
}
//在home组件中使用两个子路由
<div>
<h2>我是Home</h2>
<router-view></router-view>
<p>我是Home内容</p>
<router-link to="/home/news">News</router-link>
<router-link to="/home/message">Message</router-link>
</div>