vue.js中Vue-router 2.0基础实践教程
前言
Vue.js的一大特色就是构建单页面应用十分方便,既然要方便构建单页面应用那么自然少不了路由,vue-router就是vue官方提供的一个路由框架。本文主要介绍了Vue-router2.0的相关内容,分享出来供大家参考学习,下面来看看详细的介绍:
一、基础用法:
HelloApp!
GotoFoo GotoBar
thisisfoo!
thisisbar!
//1.定义(路由)组件。
//可以从其他文件import进来
constFoo={template:'#foo'};
constBar={template:'#bar'};
//2.定义路由
//每个路由应该映射一个组件。其中"component"可以是
//通过Vue.extend()创建的组件构造器,
//或者,只是一个组件配置对象。
constroutes=[
{path:'/foo',component:Foo},
{path:'/bar',component:Bar}
];
//3.创建router实例,然后传`routes`配置
//你还可以传别的配置参数,不过先这么简单着吧。
constrouter=newVueRouter({routes:routes});
//4.创建和挂载根实例。
//记得要通过router配置参数注入路由,
//从而让整个应用都有路由功能
constapp=newVue({router:router}).$mount('#app');
二、动态路由匹配:
HelloApp!
GotoFoo GotoBar
User:{{$route.params.id}},Post:{{$route.params.post_id}}
//1.定义组件。
constUser={
template:'#user',
watch:{
'$route'(to,from){
console.log('从'+from.params.id+'到'+to.params.id);
}
}
};
//2.创建路由实例(可设置多段路径参数)
constrouter=newVueRouter({
routes:[
{path:'/user/:id/post/:post_id',component:User}
]
});
//3.创建和挂载根实例
constapp=newVue({router:router}).$mount('#app');
三、嵌套路由:
HelloApp!
GotoFoo Gotoprofile Gotoposts