一、通过引入vue-router.js的方式使用
1.单层路由
const chinese = { template: '<div class="main">汉语</div>' }
const english = { template: '<div class="main">英语</div>' }
const app = new Vue({
router: new VueRouter({
routes: [
{ path: '/chinese', component: chinese },
{ path: '/english', component: english },
// 重定向
{path: '/',redirect: '/chinese'}
]
})
}).$mount('#app')
//访问chinese
this.$router.push('/chinese')
2.嵌套路由
contst router = new vueRouter({
routes: [
{path: '/', redirect: '/index'},
{path: '/index', component: Vue.component('index')},
{path: '/parent', name: 'parent', component: Vue.component('parent'),
children: [{
// 当 /parent/:id/child 匹配成功,
// child 会被渲染在 parent 的 <router-view> 中
//注意: 以 / 开头的嵌套路径会被当作根路径
path: 'child',
component: child,
meta: {
}
}]
}
]
})
const app = new Vue({
router
}).$mount('#app')
//访问child
this.$router.push('/parent/child')
二、vue-cli构建项目,路由使用(嵌套路由同上)
import Vue from 'vue'
import Router from 'vue-router'
Vue.use(Router)
export default new Router({
routes: [
{
path: '/',
redirect:'/index'
},
{
path: '/index',
name: 'index',
component: () => import(/* webpackChunkName: "about" */ './views/Home.vue'),
meta:{
title:''
}
},
{
path: '/quizzes',
name: 'quizzes',
component: () => import('./views/Quizzes.vue'),
meta:{
title:''
}
},
{
path: '/testresult',
name: 'testresult',
component: () => import('./views/TestResult.vue'),
meta:{
title:''
}
}
]
})
三、 vue-router传参、接参
方法一:拼接在url后边
// 传递单个参数:id
this.$router.push('/studentInfo?id=' + 1);
// 获取参数id
this.$route.query; // {id:1}
//或
this.$route.query.id // 1
// 传递参数多个参数:id,name
this.$router.push('/studentInfo?id=' + 1 + '&name=' + 2);
// 获取参数
this.$route.query;// {id:1,name:2}
方法二:对象方式
// 传递参数,路径path用query传参
this.$router.push({path:'/studentInfo',query:{id:0,name:'haha'}});
// 获取参数
this.$route.query // {id:0,name:'haha'}
// 传递参数,name用params传参
this.$router.push({ name: 'studentInfo', params: { id: 0, name: 'haha' } });
// 获取参数
this.$route.params // {id:0,name:'haha'}