Vue Router
路由是有两种模式
history模式 历史记录 /xxx/xxx/xx RESTful跟后台对接接口的一种形式
要使用这种模式必须后台配合
hash模式 锚点 #xxx
const router = new VueRouter({
mode:'history',
routes
})
目录构建
views
页面级的组件
components
小组件、公用的组件
// 路由跳转
<router-link tag="button" to="/">Home</router-link> |
<router-link to="/about/aaa">About</router-link>|
<!-- <router-link to="/list?a=1&b=2">List</router-link> -->
<!-- <router-link :to="{path:'/list',query:data}">List</router-link> -->
<router-link :to="{name:'List', path:'/list',params:data}">List</router-link>
//在需要展示的地方
<router-view/>
传递数据
动态路由
在路由配置中
routes=[
{path:'/xxx/:变量'}
]
<router-link to="/about/变量值"><router-link>
this.$router.push('about/aaa')
获取
this.$route.params.变量
类似get的传参 ?a=1&b=2
<router-link to="/about?a=1&b=2"><router-link>
<router-link :to="{path:'/about',query:{a:1}}"><router-link>
this.$route.query.a
类似post
<router-link :to="{name:'List',path:'/list',params:data}">List</router-link>
使用
this.$route.params
用js去操作跳转页面的写法
this.$router.push('about/aaa')
this.$router.push({path:'about/aaa'})
this.$router.push({name:'About',path:'about/aaa'})
this.$router.push({path:'list',query:{a:1}})
this.$router.push({path:'list',name:'List',params:{a:1}})
以上都是添加一条历史记录
this.#router.replace('about')
this.$router.go(1) -1 1前进一页 -1后退一页
路由守卫 路由的钩子函数
组件定义的时候配置
beforeRouteEnter(to,from,next){
console.log(to,from,next)
console.log('进来了')
next();
},
beforeRouteLeave(to,from,next){
console.log('离开了')
console.log(to,from,next)
next();
}
路由配置的地方
beforeEnter(to,from,next){
console.log(to,from);
next();
},
beforeLeave(){
}
import Vue from 'vue'
import VueRouter from 'vue-router'
import Home from '../views/Home.vue'
Vue.use(VueRouter)
const routes = [
{
path: '/',
name: 'Home',
component: Home
},
{
path: '/about/:id',
name: 'About',
// route level code-splitting
// this generates a separate chunk (about.[hash].js) for this route
// which is lazy-loaded when the route is visited.
component: () => import(/* webpackChunkName: "about" */ '../views/About.vue')
},
{
path: '/list',
name: 'List',
component: () => import('../views/List.vue'),
children:[
{
path:'aaa',
name:'Aaa',
component:() => import('../views/Aaa.vue')
},
{
path:'bbb',
name:'Bbb',
component: () => import ('../views/Bbb.vue')
}
]
}
]
const router = new VueRouter({
mode: 'history',
routes
})
export default router