一、配置路由
//1.创建组件(组件均被创建完成)
import Home from './components/Home.vue';
import News from './components/News.vue';
import Content from './components/Content.vue';
import User from './components/User.vue';
import UserAdd from './components/User/UserAdd.vue';
import Userlist from './components/User/Userlist.vue';
//2.配置路由 注意:名字
const routes = [
{ path: '/home', component: Home },
{ path: '/news', component: News, name: 'news' },//具名路由
{
path: '/user',
component: User,
children: [
{ path: 'useradd', component: UserAdd },//嵌套路由
{ path: 'userlist', component: Userlist }
]
},
{ path: '/content/:aid', component: Content }, /*动态路由*/
{ path: '*', redirect: '/home' } /*默认跳转路由*/
]
//3.实例化VueRouter 注意:名字
const router = new VueRouter({
mode: 'history', /*hash模式改为history*/
routes // (缩写)相当于 routes: routes
})
//4、挂载路由
new Vue({
el: '#app',
router,
render: h => h(App)
})
二、路由的使用
1、<router-link to="/home">首页</router-link>
2、<router-view></router-view>//路由视图标签调用默认路由
//使用路由传参
//'item.aid'为传入的参数
3、<router-link :to="'/content/'+item.aid">{{item.title}}</router-link>
//使用具名路由进行跳转
//跳转至‘/news’
4、this.$router.push({ name: 'news'})
//使用路由传参
//'495'为传入的参数
5、 this.$router.push({ path: '/content/495' });
//使用对象向路由中传参
6、 router.push({ name: 'news', params: { userId: 123 }})
三、路由的参数接收
//‘aid’为要接收的参数,在配置路由时创建
var aid=this.$route.params.aid;