赞
踩
1.路由就是用来解析URL实现不同页面之间的跳转
vue-router通过hash与History interface两种方式实现前端路由,更新视图但不重新请求页面”是前端路由原理的核心之一,目前在浏览器环境中这一功能的实现主要有两种方式
const routes = [ { path: '/', redirect: '/recommend' }, { path: '/recommend', component: () => import('../components/recommend/view.vue') }, { path: '/singer', component: () => import('../components/singer/view.vue') }, { path: '/rank', component: () => import('../components/rank/view.vue') }, { path: '/search', component: () => import('../components/search/view.vue') } ] export default routes
安装:
1 .安装
npm install vue-router --save
2 .main.js中
//Vue路由:引入
import VueRouter from 'vue-router'
Vue.use(VueRouter)
在浏览器中符号的“#”,以及#后面的字符称之为hash,用window.location.hash读取;
特点:
hash虽然在URL中,但不被包括在HTTP请求中;用来指导浏览器动作,对服务端安全无用,
hash不会重加载页面。
hash 模式下,仅 hash 符号之前的内容会被包含在请求中,如 http://www.xxx.com,因此对于后端来说,即使没有做到对路由的全覆盖,也不会返回 404 错误。
import Vue from 'vue'
import Router from 'vue-router'
import routes from './routes'
Vue.use(Router)
export default new Router({
// mode: 'history',
routes
})
history采用HTML5的新特性;且提供了两个新方法:pushState(),
replaceState()可以对浏览器历史记录栈进行修改,以及popState事件的监听到状态变更。
特点:
history 模式下,前端的 URL 必须和实际向后端发起请求的 URL 一致,如 地址后加上/items/id。后端如果缺少对 /items/id 的路由处理,将返回 404 错误。
这种模式充分利用 history.pushState API 来完成 URL 跳转而无须重新加载页面。
const router = new VueRouter({
mode: 'history',
routes: [...]
})
第一种跳转方式:编程式导航
{path: '/news', component: BYNews},
this.$router.push({path:'news'});
带参:
{path: '/newDetail/:aid', component: BYNewDetail},
this.$router.push({path:'/newDetail/495'});
第二种跳转方式:命名路由
{path: '/news', component: BYNews,name:'news'},
this.$router.push({name:'news'});
带参:
this.$router.push({name:'news',params:{userId:123}});
如何传参:
分别是query,params,动态路由传参
接收:
通过query方式传递过来的参数一般是通过
this.$route.query
接收
通过params方式传递过来的参数一般是通过this.$route.params
接收
通过动态路由传参方式传递过来的参数一般是通过this.$route.params
接收
query使用path和name传参跳转都可以,而params只能使用name传参跳转。
传参跳转页面时,query不需要再路由上配参数就能在新的页面获取到参数,params也可以不用配,但是params不在路由配参数的话,当用户刷新当前页面的时候,参数就会消失。
也就是说使用params不在路由配参数跳转,只有第一次进入页面参数有效,刷新页面参数就会消失。
路由守卫:
2.路由守卫使用的方式有几种? 全局的 单个路由独享的 组件级的
3.vue-router全局有三个守卫:
router.beforeEach 全局前置守卫 进入路由之前
router.beforeResolve 全局解析守卫(2.5.0+) 在beforeRouteEnter调用之后调用 router.afterEach 全局后置钩子 进入路由之后 ,
组件内的守卫:
beforeRouteEnter
beforeRouteUpdata(2.2新增)
beforeRouteLeave
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。