History API 与 vue-router路由中#的解析

URL(Universal Resource Locator)即统一资源定位符,又称网页地址,用于定位浏览器中所需显示的网页资源。

在 H5 之前,即使采用的是脚本语言的方式,只要浏览器地址栏中的 URL 地址被切换,都会触发一个页面刷新的过程,这个过程将耗费一些时间与资源。在很多时候,尤其是两个大部分内容相同的页面之间进行切换时,这个过程往往被视为一种浪费。

History API

H5 的 History API 允许在不刷新页面的前提下,通过脚本语言的方式来进行页面上某块局部内容的更新。

vue-router 默认 hash 模式 —— 使用 URL 的 hash 来模拟一个完整的 URL,于是当 URL 改变时,页面不会重新加载。

 

 

 

如果不想要很丑的 hash,我们可以用路由的 history 模式,这种模式充分利用 history.pushState API 来完成 URL 跳转而无须重新加载页面。

/* jshint esversion: 6 */
import VueRouter from "vue-router";
import Vue from 'vue';
import Order from '@/components/Order';
import Home from '@/components/Home';
import My from '@/components/My';

Vue.use(VueRouter);

const routes = [
    {
        path: '/',
        component:Home,
        name: 'home'
    },
    {
        path: '/order',
        component:Order,
        name: 'order'
    },
    {
        path: '/mine',
        component:My,
        name: 'mine'
    },
];

// 添加mode为history就不会有#
const router = new VueRouter({
    mode: 'history',
    routes
});

export default router;

 

当你使用 history 模式时,URL 就像正常的 url

 

 

不过这种模式要玩好,还需要后台配置支持。因为我们的应用是个单页客户端应用,如果后台没有正确的配置,当用户在浏览器直接访问 http://oursite.com/user/id 就会返回 404,这就不好看了。

所以呢,你要在服务端增加一个覆盖所有情况的候选资源:如果 URL 匹配不到任何静态资源,则应该返回同一个 index.html 页面,这个页面就是你 app 依赖的页面。

posted @ 2020-10-24 14:32  一文g  阅读(393)  评论(0编辑  收藏  举报