现在的位置: 首页 > 数据库 > 正文

之三Vue-router前端路由与“#”

2020年02月12日 数据库 ⁄ 共 2092字 ⁄ 字号 评论关闭

前端路由,将本来根据地址请求后端返回页面,变为了前端直接重新渲染页面。

优点:用户体验好,不需要每次都从服务器全部获取,快速展现给用户

缺点:不利于SEO;使用浏览器的前进、后退键会重新发送请求,没有合理地利用缓存;单页面无法记住之前滚动的位置,无法在前进、后退的时候记住滚动的位置。

vue-router 是构建vue SPA的关键

通常,我们使用<router-link></router-link> 与<router-view></router-view> 。

<router-link> 负责路由的跳转,它的 “to” 属性指定跳转的地址。

<router-view> 负责路由的渲染。

 

认识一点,vue-router 就是对浏览器中提供的history API 的封装,感兴趣可以了解history API。

 

动态路由匹配

动态路由,是指路由地址中含有变量的那种路由,比如下面

 

下面是一个动态路由的例子。

首先我们先写个普通路由。

页面,代码如下。

<template> <p>这是商品列表页</p></template><script>export default { name: 'GoodList'}</script><style scoped></style>

router文件夹下 index.js 代码如下。

import Vue from 'vue'import Router from 'vue-router'import GoodList from '@/views/GoodList'Vue.use(Router)export default new Router({ routes: [{ path: '/', name: 'GoodList', component: GoodList }]})

就好啦。启动一下服务器就可以看到啦。

下面我们做一个动态路由的例子。

首先,我们规定一个url 地址,下面是router 文件夹下的index.js 代码。

import Vue from 'vue'import Router from 'vue-router'import GoodList from '@/views/GoodList'Vue.use(Router)export default new Router({ routes: [{ path: '/goods/:goodsId', name: 'GoodList', component: GoodList }]})

然后我们在GoodList.vue 中修改代码,如下。

<template> <p> 这是商品列表页 <span>{{$route.params.goodsId}}</span> </p></template><script>export default { name: 'GoodList'}</script><style scoped></style>

如上,复合规则的url 将会改变页面。

再复杂一些的动态路由,router/index.js如下。

import Vue from 'vue'import Router from 'vue-router'import GoodList from '@/views/GoodList'Vue.use(Router)export default new Router({ routes: [{ path: '/goods/:goodsId/user/:name', name: 'GoodList', component: GoodList }]})

GoodList.vue 代码如下。

<template> <p> 这是商品列表页 <span>{{$route.params.goodsId}}</span> <br /> <span>{{$route.params.name}}</span> </p></template><script>export default { name: 'GoodList'}</script><style scoped></style>

好啦。

可以看到,在地址栏,我们的地址是这样的: http://localhost:8080/#/goods/89/user/nnn

有一个“#” 号。这实际上是一种路由的哈希。地址可以分两种模式:history(直接用url 地址),哈希(默认,hash)。

这个在router 下面的index.js 中是可以修改的。如下。

import Vue from 'vue'import Router from 'vue-router'import GoodList from '@/views/GoodList'Vue.use(Router)export default new Router({ mode: 'history', routes: [{ path: '/goods/:goodsId/user/:name', name: 'GoodList', component: GoodList }]})

然后,就可以用这种地址 http://localhost:8080/goods/89/user/nnn 访问了。

以上就上有关之三Vue-router前端路由与“#”的相关介绍,要了解更多php教程_php自学_php视频教程下载 - 绵阳技术博客内容请登录学步园。

抱歉!评论已关闭.