安装
介绍
使用模板引擎(vuejs),我们实现了通过组合组件来组成应用程序。
使用路由引擎(vue-router),实现把组件与路由联系起来。
使用
// 1.定义组件
const Foo = { template: '<div>foo</div>' }
const Bar = { template: '<div>bar</div>' }
// 2.定义路由
const routes = [
{ path: '/foo', component: Foo },
{ path: '/bar', component: Bar }
]
// 3.创建路由器(组件和路由握手)
const router = new VueRouter({
routes // 缩写 routes: routes
})
// 4.挂载根实例(路由引擎和模板引擎握手)
const app = new Vue({
router
}).$mount('#app')
参考
//定义路由-静态路由(一个路由对应一个组件)
{ path: '/foo', component: Foo }
//定义路由-动态路由(多个路由对应一个组件)
//(路径参数)
{ path: '/user/:id', component: User }
//定义路由-匿名路由
{ path: '/user/:id', component: User}
//定义路由-命名路由
{ path: '/user/:id', component: User,name: 'user' }
//定义路由-别名路由(多个路由对应一个组件)
{ path: '/a', component: A, alias: '/b' }
//定义路由-定向路由(多个路由对应一个组件)
//(重新定向)
{ path: '/a', redirect: '/b' }//字符
{ path: '/a', redirect: { name: 'foo' }}//对象
{ path: '/a', redirect: to=>{return '/b'}}//函数
{ path: '/a', redirect: to=>{return { name: 'foo' }}}
// 用户访问 /a时,URL将会被替换成 /b,然后匹配路由为 /b
//定义路由-嵌套路由(一个路由,多个视图,视图嵌套)
{ path: '/user/:id', component: User,
children: [
{
// 当 /user/:id/profile 匹配成功,
// UserProfile 会被渲染在 User 的 <router-view> 中
path: 'profile',
component: UserProfile
},
{
// 当 /user/:id/posts 匹配成功
// UserPosts 会被渲染在 User 的 <router-view> 中
path: 'posts',
component: UserPosts
}
]
}
//定义路由-命名视图(一个路由,多个视图,视图同级)
{
path: '/',
components: {
//默认
default: Foo,
//视图名字a
a: Bar,
b: Baz
}
}
//定义路由-嵌套视图
{
path: '/settings',
component: UserSettings,
children: [
//"/settings/emails"=>UserEmailsSubscriptions
{
path: 'emails',
component: UserEmailsSubscriptions
},
//"/settings/profile"=>UserProfile
{
path: 'profile',
components: {
default: UserProfile,
helper: UserProfilePreview
}
}]
}
//定义路由-数据路由(传递数据)
{
path: '/user/:id',
components: { default: User, sidebar: Sidebar },
props: { default: true, sidebar: false }
}
// 定义链接-声明式
<router-link :to="{name: 'user',params: {userId:123 }}">User</router-link>
// 定义链接-编程式
//方式2 router.push(location, onComplete?, onAbort?)
router.push({name:'user', params:{ userId: 123 }})
// 定义钩子-全局-前置
router.beforeEach((to,from, next)=> {
// ...
//进入下个钩子:next()
//中断当前钩子:next(false)
//跳转其他路由:next('/');//next({ path: '/' })
})
// 定义钩子-全局-后置
router.afterEach((to,from) =>{
//...
})
// 定义钩子-路由-前置
{
path: '/foo',
component: Foo,
beforeEnter: (to, from,next)=> {
// ...
}
}
// 定义钩子-组件-前置
{
template: '<div>foo</div>'
beforeRouteEnter: (to, from,next)=> {
// ...
}
}
// 访问路由-组件内
this.$route
// 定义视图-命名视图
<router-view></router-view>
<router-view name="a"></router-view>
<router-view name="b"></router-view>
访问路由器-组件内
this.$router
// 定义路由-获取数据
// 导航完成之前获取:导航完成前,在路由进入的守卫中获取数据,在数据获取成功后执行导
航。
// 定义组件-获取数据
// 导航完成之后获取:先完成导航,然后在接下来的组件生命周期钩子中获取数据。在数据获取
期间显示『加载中』之类的指示。
网友评论