Vue-router对象配置
路由重定向:【redirect:'/app'】
mode模式:可修改为history(不显示#)。
linkActiveClass:指定被选择时的样式名称。
const router = new VueRouter({
routes,
mode:'history',
linkActiveClass:'aaa'
})
router-link属性
tag标签:指定router-link转为特定标签。(默认是a标签)。
replace:该属性相当于使用history.replaceState()。(不会产生history路由)
active-class:被选择时使用该属性值作为class。
<template>
<div id="app">
<router-link to="/home" replace tag="span" active-class="bbb">首页router-link> |
<router-link to="/about">关于router-link>
<router-view>router-view>
div>
template>
通过代码跳转路由
VueRouter在所有组件中都增加了$router属性。
通过this.$router.push('/')或者this.$router.replace('/about')跳转路由。
<script>export default{name:'App',methods:{
b1(){this.$router.push('/home')
},
b2(){this.$router.push('/about')
}
}
}script>
动态路由
动态路由是指路由中的部分路径是可变的。
在路由文件中配置path:'/user/:userid'实现动态路由。
配置router-link时,可以通过v-bind绑定动态的值。
在vue页面中通过this.$route.params.userid获取路由中的值。
this.$routers是VueRouter对象,this.$route是当前活跃路由对象。
// About.vue
<template>
<div>
<h1>这里是Abouth1>
<p>这里是About内容2p>
<span>{{$route.params.uid}}span>
div>
template>
// router/index.js
const routes = [
{
path: '/about/:uid',
component:About
}
]
// App.vue
<script>export default{name:'App',
data(){return {uid:'zhangsan'
}
},methods:{
b2(){this.$router.push('/about/' + this.uid )
}
}
}script>
路由的懒加载
当打包构建应用时,Javascript包非常大影响页面加载。
使用懒加载后,它会将路由对应的组件分割成不同代码块,路由被访问时才加载对应组件。
不使用懒加载,打包后的JS对应功能:【app.js-业务模块】、【main-底层导入导出依赖等】、【vendors-第三方依赖】。
懒加载写法一:结合Vue的异步组件和Webpack的代码分析。(认识这种写法即可,该写法已经过时)
const Home = resolve => { require.ensure(['../components/Home.vue'], () => { resolve(require('../components/Home.vue'))})};
懒加载写法二:AMD写法。
const About = resolve => require(['../components/About.vue'],resolve);
懒加载写法三:在ES6中更加简单的写法。(推荐使用这种写法)
const Home = () => import('../components/Home.vue')