您的位置:首页 > 产品设计 > UI/UE

vue.js 2.0系列之 路由的使用

2018-01-27 22:39 597 查看

1,首先下载vue-router

npm install vue-router --save


4000

2,引入并use

import Vue from "vue"
import Router from "vue-router"
Vue.use(Router)




在template中的使用:

keep-alive可以缓存组件,提高渲染效率。保持用户对页面的修改

<keep-alive>
<router-view></router-view>
</keep-alive>


router-link可以使改变路由,

:to=”{ path: item.path }” 表示要跳转的路径

tag=”li” 表示最中渲染成li

<ul>
<router-link v-for="(item,index) in products"
:key="index"
:to="{ path: item.path }"
tag="li"
active-class="active">
{{ item.name }}
</router-link>
</ul>


3,获取路由参数

路由配置

routes: [
{
path: '/home/:cur',
component: index
},


在js里姐可以使用$route获取参数

this.$route.path   //cur


4,导航守卫

路由跳转前做一些验证,比如登录验证(未登录去登录页),是网站中的普遍需求

const vueRouter = new Router({
routes: [
//......
{
path: '/account',
name: 'account',
component: Account,
children: [
{name: 'course', path: 'course', component: CourseList},
{name: 'order', path: 'order', component: OrderList}
]
}
]
});
vueRouter.beforeEach(function (to, from, next) {
const nextRoute = [ 'account', 'order', 'course'];
const auth = store.state.auth;
//跳转至上述3个页面
if (nextRoute.indexOf(to.name) >= 0) {
//未登录
if (!store.state.auth.IsLogin) {
vueRouter.push({name: 'login'})
}
}
//已登录的情况再去登录页,跳转至首页
if (to.name === 'login') {
if (auth.IsLogin) {
vueRouter.push({name: 'home'});
}
}
next();
});


5,js里改变路由

this.$router.push({path: '/coach/' + this.$route.params.id, query: queryData});


6,视图中制定不同的组件

在路由配置中:



template中:


7,路由重定向

内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: