在router/index.js中,设置路由器规则,匹配路由
import Vue from 'vue'
import VueRouter from 'vue-router'
import HomeView from '../views/HomeView.vue'
Vue.use(VueRouter)
routers表示路由表
routers数组中的每一个对象都对应着一条路由规则
并且每个对象都有两个必填属性path和component
path表示路由地址,component表示路由地址对应的页面视图文件
const routes = [
{
// 这里就表示当地址是"localhost:8080/#/",就进入HomeView界面
path: '/',
name: 'home',
component: HomeView
},
{
path: '/about',
name: 'about',
// route level code-splitting
// this generates a separate chunk (about.[hash].js) for this route
// which is lazy-loaded when the route is visited.
component: () => import(/* webpackChunkName: "about" */ '../views/AboutView.vue')
}
]
const router = new VueRouter({
routes
})
export default router
在router/indexedDB.js文件中,我们除了定义路由规则之外
(路由规则指的是每条路径对于的视图)
还可以给每条路由规则取个名字,用名称来标识这条路由
命名路由的必要性
首先 如果地址比较长 包括低智商还会有参数时 引用这个地址就不方便
或者是 要修改某条路由规则时 相应的其他地方也要改变
import Vue from 'vue'
import App from './App.vue'
// 引入router文件,省略了"index.js"
// import router from './router/index.js'
import router from './router'
import store from './store'
// 导入全局样式
import './style/base.less'
// 导入组件(一次性导入所有组件)
import Vant from 'vant';
import 'vant/lib/index.css';
Vue.use(Vant);
Vue.config.productionTip = false
new Vue({
// 把router挂在到vue实例上
router,
store,
render: h => h(App)
}).$mount('#app')
路由的两种模式
一、hash 模式
hash模式的原理是onhashchange事件,可以通过window对象来监听该事件。
在hash模式下,当url发生变化时,浏览器会记录下来,因此前进后退按钮都可以使用。
vue-router
默认hash
模式,使用url
的哈希(hash
)来模拟一个完整的URL
,当URL
改变时,页面不会重新加载
hash模式的优缺点:
优点:浏览器兼容性较好,连 IE8 都支持
缺点:路径在井号#的后面,比较丑
二、history 模式
historv API是 H5 提供的新特性,允许开发者直接更改前端路由,即更新浏览器 URL地址而不重新发起请求。
history
模式:在实例化配置对象中添加mode
模式,值为history
就可以了的 经过改造后,hash
模式就会变成history
模式
history模式的优缺点:
优点:路径比较正规,没有井号 #
缺点:兼容性不如 hash,目需要服务端支持,否则一刷新页面就404了
三、总结
前端路由,有两种模式,一种是hash
模式,另一种是history
模式,其中hash
模式是默认模式,#
后面的不会发送给服务端,不会重新刷新加载页面,而history
模式,url
虽然比较好看,但是想要完整支持,需要后端同学提供支持,后端路由与前端的路由需要做匹配否则部署到线上,一刷新页面,会出现404
的问题。