本文实例讲述了vue学习之Vue-Router用法。分享给大家供大家参考,具体如下:Vue-router就像一个路由器,将组件(components)映射到路由(routes)后,通过点击它可以在中将相应的组件渲染出来。1、使用vue-router的步骤

//1、创建路由组件

const Link1={template:'#link1'};

const Link2={template:'#link2'};

const Link3={template:'#link3'};

//2、定义路由映射

const routes=[

{

path:'/link1',
//定义相对路径

component:Link1,
//定义页面的组件

children:[

{

path:'intro',
//子路由/link1/intro

component:{template:'#ariesIntro'},

name:'ariesIntro',
//为路由命名

},

{

path:'feature',

component:{template:'#ariesFeature'},

},

{path:'/',redirect:'intro'}

]

},

{path:'/link2',component:Link2},

{path:'/link3',component:Link3},

{path:'/',redirect:'/link1'}
//配置根路由,使其重定向到/link1

];

//3、创建router实例

const router = new VueRouter({

routes
//缩写,相当于 routes: routes

});

// 4、 创建和挂载根实例。

const app = new Vue({

router

}).$mount('#app');
//挂载到id为app的div



//1、创建路由组件

const Link1={template:'#link1'};

const Link2={template:'#link2'};

const Link3={template:'#link3'};

//2、定义路由映射

const routes=[

{

path:'/link1',
//定义相对路径

component:Link1,
//定义页面的组件

children:[

{

path:'intro',
//子路由/link1/intro

component:{template:'#ariesIntro'},

name:'ariesIntro',
//为路由命名

},

{

path:'feature',

component:{template:'#ariesFeature'},

},

{path:'/',redirect:'intro'}

]

},

{path:'/link2',component:Link2},

{path:'/link3',component:Link3},

{path:'/',redirect:'/link1'}
//配置根路由,使其重定向到/link1

];

//3、创建router实例

const router = new VueRouter({

routes
//缩写,相当于 routes: routes

});

// 4、 创建和挂载根实例。

const app = new Vue({

router

}).$mount('#app');
//挂载到id为app的div

注意:要设置根路由,页面加载完成后默认显示根路由,否则将什么也不显示。在页面中调用路由接口, 默认会被渲染成一个 `` 标签,点击后在渲染指定模板







白羊座

处女座

金牛座



























白羊座

处女座

金牛座



















2、嵌套路由通过每个路由内的children数组属性可以为每个路由再配置子路由,子路由的路径是基于父路由目录下的,默认路径会进行叠加。例如上面再link1中添加intro与feature两个子路由,在link1模板中使用两个子路由:







最终效果如图:3、动态路由在路由路径中绑定变量,使其根据不同的变量值跳转到不同页面,例如将path:"goods/:goodsId",假如当goodsId为15时,就会路由到/goods/15页面。4、编程路由通过js代码控制路由页面的跳转与传值。例如给button绑定事件jump,在methods内实现:
jump(){

this.$router.push('/cart?goodsId=123')
}


jump(){

this.$router.push('/cart?goodsId=123')
}

页面跳转到根下的cart目录,并且传递参数goodsId,值为123。在cart页面通过$route.query接收参数,直接在页面内使用:注意:区分跳转是$router,接收参数是$route
商品ID:{{$route.query.goodsId}}


商品ID:{{$route.query.goodsId}}

也可以指定页面向前向后跳转:this.$router.go(2),向前跳转两步 ,向后跳转一步go(-1)。5、命名路由当路由路径过长时,也可以用name属性为路径命名,在中使用动态绑定:to="{name:'路径名'}"访问。例如白羊座的链接上使用 :to="{name:'ariesIntro'}",可直接跳转到link1下的Intro页面。还可以对视图进行命名,将组件渲染到指定视图位置,例如在父组件中有一个默认视图与两个命名视图一左一右:










在根路由中设置其组件components,将默认视图渲染为GoodsList,左边cartview视图渲染为Cart组件,右边imgview渲染为Image组件:
new Router({
routes: [

{

path: '/',

components:{

default:GoodsList,

cartview:Cart,

imgview:Image

}
}


new Router({
routes: [

{

path: '/',

components:{

default:GoodsList,

cartview:Cart,

imgview:Image

}
}

结果如下:希望本文所述对大家vue.js程序设计有所帮助。