前端vue2、vue3去掉url路由“ # ”号——nginx配置

news2024/9/27 9:22:17

文章目录

    • ⭐前言
    • ⭐vue2中router默认出现#号
      • 💖在vue2项目中去掉
      • 💖在vue3项目中去掉
    • ⭐vue打包 assetsPublicPath base 为绝对路径 /
      • 💖vue2 配置 assetsPublicPath
      • 💖vue3 配置 base
      • 💖验证
    • ⭐nginx 配置
      • 💖 使用默认的nginx 静态资源文件夹
      • 💖 自定义静态资源文件夹
    • ⭐结束

yma16-logo

⭐前言

大家好,我是yma16,本文分享关于vue2、vue3去掉url路由 # 号——nginx配置。
html的 hash模式

HTML的hash模式指的是URL中的锚点部分(#后面的内容)被用于在单个页面中显示不同的内容,而不是导航到不同的页面。例如:

https://example.com/#about

在这个示例中,#about部分是一个锚点,用于在页面上显示关于页面的内容,而不是导航到一个新的页面。

在使用hash模式时,可以使用JavaScript监听hashchange事件,以便在锚点改变时执行相应的操作。这种模式常用于单页面应用程序(SPA),其中所有页面内容都在同一个HTML页面中加载,而不是通过导航到新页面来加载。此外,hash模式还可以用于在不刷新整个页面的情况下更改URL,以便在浏览器历史记录中创建可回退的状态。

html的 history模式

HTML5中的History API允许使用JavaScript动态更新URL并在历史记录中保存状态,而不会刷新整个页面。这就是所谓的“history模式”。它使用HTML5的pushState和replaceState方法来添加或修改浏览器历史记录中的条目。

在history模式下,URL的路径部分会随着用户的操作而变化,但实际页面内容不会刷新,这使得Web应用程序更具交互性和可访问性。

如果浏览器支持History API,那么就可以使用history.pushState()和history.replaceState()方法来更新浏览器的URL路径,从而可以实现前端路由,而不用像传统的多页面应用一样每次都请求服务器获取新的HTML页面。

⭐vue2中router默认出现#号

路由配置默认出现 #
vue2——#

💖在vue2项目中去掉

关键配置

    // 路由
    const router = new VueRouter({
        mode: 'history',
        routes
    })

router的配置

import { isEmpty } from '@/utils'
import store from '@/store'

const Login = () => import('@/components/user/Login')
const Register = () => import('@/components/user/Register')
const Onlinewebsocket = () => import('@/components/websocket/Onlinewebsocket')

const Home = () => import('@/components/Home')
const Bilicom = () => import('@/components/Bilicom')
const Mavoneditor = () => import('@/components/Mavoneditor')
const GrilShow = () => import('@/components/GrilShow')

const Csslearn = () => import('@/views/cssView/Csslearn')
const Article = () => import('@/views/article/Article')
const defaultRoutes = [
    {
        path: '/',
        name: 'Article',
        component: Article,
        hidden: true
    },
    {
        path: '/login',
        name: 'Login',
        component: Login,
        hidden: false
    },
    {
        path: '/register',
        name: 'Register',
        component: Register,
        hidden: false
    },
    {
        path: '/home',
        name: 'Home',
        component: Home,
        hidden: true
    },
    {
        path: '/onlinewebsocket',
        name: 'Onlinewebsocket',
        component: Onlinewebsocket,
        hidden: true
    },
    {
        path: '/mavoneditor',
        name: 'Mavoneditor',
        component: Mavoneditor,
        hidden: true
    },
    {
        path: '/gril',
        name: 'grilshow',
        component: GrilShow,
        hidden: true
    },
    {
        path: '/css',
        name: 'css',
        component: Csslearn,
        hidden: true
    }
]

const useRouter = (Vue, VueRouter) => {
    let routes = [
        ...defaultRoutes
    ]
    const originalPush = VueRouter.prototype.push
    VueRouter.prototype.push = function push (location) {
        return originalPush.call(this, location).catch((err) => err)
    }
    // 路由
    const router = new VueRouter({
        mode: 'history',
        routes
    })

    router.beforeEach(async (to, from, next) => {
        let yma16siteUserInfo = localStorage.getItem('yma16siteUserInfo')
            ? JSON.parse(localStorage.getItem('yma16siteUserInfo'))
            : {}
        let name = yma16siteUserInfo.username
        let pwd = yma16siteUserInfo.password
        let thirdUserInfo = yma16siteUserInfo.thirdUserInfo

        console.log('to', to)
        let hasToken = {
            name: name,
            password: pwd,
            thirdUserInfo: thirdUserInfo
        }
        console.log('localStorage', hasToken)
        if (hasToken.name && hasToken.password) {
            if (!isEmpty(store.state.user.userInfo)) {
                try {
                    // 空的 modules下的user
                    console.log('路由的登录认证')
                    // 用户自主登录
                    await store.dispatch('user/loginUserInfo', hasToken)
                    next()
                } catch (e) {
                    console.error(e, 'e')
                    if (to.name === 'Login' || to.path === '/login' || to.name === 'register' || to.path === '/Register') {
                    // 避免同名路由无限循环
                        console.log('next')
                        next()
                    } else {
                        console.log('login router')
                        return next({ name: 'Login' }) // 去登录
                    }
                }
            } else {
                console.log('next')
                next()
            }
        } else if (to.name === 'Login' || to.path === '/login' || to.name === 'Register' || to.path === '/register') {
            console.log('next login register')
            // 避免同名路由无限循环
            next()
        } else {
            console.log('login router')
            return next({ name: 'Login' }) // 去登录
        }
        return false
    })

    Vue.use(VueRouter)
    return router
}

export default useRouter

效果 url 没有 # 号

drop #

💖在vue3项目中去掉

import { createRouter, createWebHashHistory } from 'vue-router'

const router = createRouter({
  history: createWebHashHistory(),
  routes: [
    //...
  ],
})

createWebHashHistory变成createWebHistory

import { createRouter, createWebHistory } from 'vue-router'

const router = createRouter({
  history: createWebHistory(),
  routes: [
    //...
  ],
})

⭐vue打包 assetsPublicPath base 为绝对路径 /

💖vue2 配置 assetsPublicPath

"use strict";
// Template version: 1.3.1
// see http://vuejs-templates.github.io/webpack for documentation.

const path = require("path");

module.exports = {
  dev: {
    // Paths
    assetsSubDirectory: "myblog_static",
    assetsPublicPath: "/",
    proxyTable: {
      "/api/": {
        target: "后端接口地址", //后端接口地址
        ws: true, //接受websocket请求
        changeOrigin: true, //是否允许跨越
        chunkOrigins: true,
        pathRewrite: {
          "^/api": "api", //重写,
        },
      },
    },

    // Various Dev Server settings
    host: "localhost", // can be overwritten by process.env.HOST
    port: 8080, // can be overwritten by process.env.PORT, if port is in use, a free one will be determined
    autoOpenBrowser: false,
    errorOverlay: true,
    notifyOnErrors: true,
    poll: false, // https://webpack.js.org/configuration/dev-server/#devserver-watchoptions-

    // Use Eslint Loader?
    // If true, your code will be linted during bundling and
    // linting errors and warnings will be shown in the console.
    useEslint: false,
    // If true, eslint errors and warnings will also be shown in the error overlay
    // in the browser.
    showEslintErrorsInOverlay: false,

    /**
     * Source Maps
     */

    // https://webpack.js.org/configuration/devtool/#development
    devtool: "cheap-module-eval-source-map",

    // If you have problems debugging vue-files in devtools,
    // set this to false - it *may* help
    // https://vue-loader.vuejs.org/en/options.html#cachebusting
    cacheBusting: true,

    cssSourceMap: true,
  },

  build: {
    // Template for index.html
    index: path.resolve(__dirname, "../dist/index.html"),
    // Paths
    assetsRoot: path.resolve(__dirname, "../dist"),
    assetsSubDirectory: "myblog_static",
    assetsPublicPath: "/",
    /**
     * Source Maps
     */
    productionSourceMap: false,
    // https://webpack.js.org/configuration/devtool/#production
    devtool: "#source-map",
    // Gzip off by default as many popular myblog_static hosts such as
    // Surge or Netlify already gzip all myblog_static assets for you.
    // Before setting to `true`, make sure to:
    // npm install --save-dev compression-webpack-plugin
    productionGzip: true,
    productionGzipExtensions: ["js", "css"],

    isIgnoreLogs:true,
    // Run the build command with an extra argument to
    // View the bundle analyzer report after build finishes:
    // `npm run build --report`
    // Set to `true` or `false` to always turn it on or off
    bundleAnalyzerReport: process.env.npm_config_report,
  },
};

💖vue3 配置 base

import { defineConfig } from "vite";
import vue from "@vitejs/plugin-vue";
// @ts-ignore
import { resolve } from "path";
// @ts-ignore
import Components from "unplugin-vue-components/vite";
// @ts-ignore
import { AntDesignVueResolver } from "unplugin-vue-components/resolvers";

// https://vitejs.dev/config/
export default defineConfig({
  // 打包相对路径
  base: '/',
  server: {
    port: 3000,
    open: true,
    cors: true,
    proxy: {
      "^/cloudApi/": {
        target: "https://yongma16.xyz/back-front/",
        // target: "http://localhost:9090/",
        changeOrigin: true,
        ws: true,
        rewrite: (path) => path.replace(/^\/cloudApi/, ""),
      },
    },
  },
  "css": {
    preprocessorOptions: {
      less: {
        javascriptEnabled: true,
        patterns: [resolve(__dirname, "./src/style/main.less")],
      },
    },
  },
  resolve: {
    alias: {
      "@": resolve(__dirname, "src"),
    },
  },
  plugins: [
    vue(),
    Components({
      resolvers: [AntDesignVueResolver()],
    }),
  ],
});

💖验证

1.检查 路径十是否都是绝对路径
2. 本地打开index.html不可取,使用http-server启动打开
检查绝对路径
dist-html
检查http-server可以运行vue而且没有#号
HTTP-SERVER
check-#

⭐nginx 配置

💖 使用默认的nginx 静态资源文件夹

  1. vue打包目录就放在 nginx 默认 html静态文件夹
location / {
  try_files $uri $uri/ /index.html;
}

💖 自定义静态资源文件夹

# 路径
location / {
	root /web-server/front-project/dist;
	try_files $uri $uri/ @router;
	index index.html index.htm;
}
# @router配置
location @router {
	rewrite ^.*$ /index.html last;
}
# 静态资源代理
location /myblog_static {
	alias /web-server/front-project/dist//myblog_static/;
}

效果:
https://yongma16.xyz/
vue-production

⭐结束

本文分享到这结束,如有错误或者不足之处欢迎指出!
ship-air

👍 点赞,是我创作的动力!
⭐️ 收藏,是我努力的方向!
✏️ 评论,是我进步的财富!
💖 感谢你的阅读!

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:http://www.coloradmin.cn/o/934603.html

如若内容造成侵权/违法违规/事实不符,请联系多彩编程网进行投诉反馈,一经查实,立即删除!

相关文章

ROS-3.ros创建工作空间和工作包

工作空间 工作空间(workspace)是存放工程开发相关文件的目录,目录里面包括 src :代码空间,ROS的catkin软件包(源代码包)build:编译空间,catkin(CMake)的缓存信息和中间…

关于事件回调机制

OVERVIEW 关于事件回调机制1.事件回调编程模式2.C中的事件回调编程模式函数指针回调函数对象回调 3.简单回调实例 关于事件回调机制 1.事件回调编程模式 当涉及到编程和软件开发时,事件回调是一种常见的编程模式。它用于处理异步事件和消息传递系统中的事件通知。 …

map set

✅<1>主页&#xff1a;我的代码爱吃辣&#x1f4c3;<2>知识讲解&#xff1a;C STL map&&set☂️<3>开发环境&#xff1a;Visual Studio 2022&#x1f4ac;<4>前言&#xff1a;map和set是C98就已经支持的两个搜索效率极高的容器&#xff0c;其底…

无涯教程-分类算法 - 随机森林

随机森林是一种监督学习算法&#xff0c;可用于分类和回归&#xff0c;但是&#xff0c;它主要用于分类问题&#xff0c;众所周知&#xff0c;森林由树木组成&#xff0c;更多树木意味着更坚固的森林。同样&#xff0c;随机森林算法在数据样本上创建决策树&#xff0c;然后从每…

高中信息技术教资考试模拟卷(22下)

2022 年下半年全国教师资格考试模考卷一 &#xff08;高中信息技术&#xff09; 一、单项选择题&#xff08;本大题共 15 小题&#xff0c;每小题 3 分&#xff0c;共 45 分&#xff09; 1.2006 年 10 月 25 日&#xff0c;深圳警方成功解救出一名被网络骗子孙某…

认识Spring AOP面向切面编程

目录 一、面向切面编程思维&#xff08;AOP&#xff09; 二、AOP思想主要的应用场景 三、AOP术语名词介绍 四、Spring AOP框架介绍和关系梳理 一、面向切面编程思维&#xff08;AOP&#xff09; AOP&#xff1a;Aspect Oriented Programming面向切面编程 AOP可以说是OOP&a…

Linux 三剑客

grep grep主打的就是查找功能 &#xff0c;它能够在一个或者多个文件中搜索某一特定的字符模式。 grep的语法 grep [选项] 模式 文件名 先说选项&#xff1a; 1.选项 要么是正则要么是字符串 -c 列出共出现多少次 -i 忽略大小写 -n 在前面列出行号 -v …

分类模型评估指标——准确率、精准率、召回率、F1、ROC曲线、AUC曲线

机器学习模型需要有量化的评估指标来评估哪些模型的效果更好。 本文将用通俗易懂的方式讲解分类问题的混淆矩阵和各种评估指标的计算公式。将要给大家介绍的评估指标有&#xff1a;准确率、精准率、召回率、F1、ROC曲线、AUC曲线。 机器学习评估指标大全 所有事情都需要评估好…

Mycat之前世今生

如果我有一个32核心的服务器&#xff0c;我就可以实现1个亿的数据分片&#xff0c;我有32核心的服务器么&#xff1f;没有&#xff0c;所以我至今无法实现1个亿的数据分片。——MyCAT ‘s Plan 话说“每一个成功的男人背后都有一个女人”&#xff0c;自然MyCAT也逃脱不了这个诅…

AI自动驾驶也“区分人种”?有色人种和儿童面临更高碰撞风险

8月27日消息&#xff0c;随着人工智能&#xff08;AI&#xff09;的快速发展&#xff0c;尤其是在自动驾驶汽车领域&#xff0c;这项技术给人类带来了巨大的便利。 然而&#xff0c;据最新的研究发现&#xff0c;自动驾驶汽车中的行人检测软件可能存在一些严重问题&#xff0c;…

章节 3:React.js基础 -《React.js手把手教程:从初学者到实战高手》- 第一部分:React.js基础

《React.js手把手教程&#xff1a;从初学者到实战高手》 第一部分&#xff1a;React.js基础 章节 3&#xff1a;React.js基础 在这一章中&#xff0c;我们将进一步了解 React.js 的基础知识。我们会从最基本的 React 组件开始&#xff0c;逐步引导你进入 React.js 的世界。 …

RocketMQ同步复制和异步复制

如果一个Broker组有Master和Slave&#xff0c;消息需要从Master复制到Slave上&#xff0c;有同步和异步两种复制方式。 1)同步复制 同步复制方式是等Master和Slave均写成功后才反馈给客户端写成功状态&#xff1b; 在同步复制方式下&#xff0c;如果Master出故障&#xff0c…

调用paddleocr接口实现文本检测与识别,并在图像中显示识别结果

目录 一、按照官网步骤安装paddlepaddle和paddleocr(paddlepaddle我安装的是cpu版本) 二、运行下面的脚本 三、图像结果 一、按照官网步骤安装paddlepaddle和paddleocr(paddlepaddle我安装的是cpu版本) doc/doc_ch/quickstart.md PaddlePaddle/PaddleOCR - Gitee.com 二、…

IDEA对Web和Tomcat的一些配置

这里只是做了自己学习中的一点记录&#xff0c;仅供参考哈&#xff01; 配置Tomcat Modules新增Web 新增module后新增Artifacts 新增Artifacts后Tomcat新增布署 将指定的module由普通java项目变成web项目 直接创建布署到Tomcat时所需要的Aritifacts包 配置Servlet的依赖包 配置…

初识【类和对象】

目录 1.面向过程和面向对象初步认识 2.类的引入 3.类的定义 4.类的访问限定符及封装 5.类的作用域 6.类的实例化 7.类的对象大小的计算 8.类成员函数的this指针 1.面向过程和面向对象初步认识 C语言是面向过程的&#xff0c;关注的是过程&#xff0c;分析出求解问题的…

Java进阶篇--创建线程的四种方式

目录 继承Thread类 扩展小知识&#xff1a; Thread类的常见方法 Thread 类的静态方法 实现Runnable接口 使用Callable和Future创建线程 使用Executor框架创建线程池 继承Thread类 创建一个继承自Thread类的子类&#xff0c;并重写其run()方法&#xff0c;将相关逻辑实现…

Flink CDC数据同步

背景 随着信息化程度的不断提高&#xff0c;企业内部系统的数量和复杂度不断增加&#xff0c;因此&#xff0c;数据库系统的同步问题已成为越来越重要的问题。 缓存失效 在缓存中缓存的条目(entry)在源头被更改或者被删除的时候立即让缓存中的条目失效。如果缓存在一个独立的…

“返璞归真,数字排毒”,放下智能手机,美国功能手机卷土重来

近年来&#xff0c;智能手机的普及已经改变了人们的生活方式和沟通方式。然而&#xff0c;随着科技的不断进步和不断涌现的各种新应用程序&#xff0c;一些年轻人开始感到疲惫和厌倦。他们觉得智能手机带来了太多的干扰和依赖&#xff0c;也让人们容易沉迷于社交媒体和短视频。…

Rabbitmq的Federation Exchange

(broker 北京 ) &#xff0c; (broker 深圳 ) 彼此之间相距甚远&#xff0c;网络延迟是一个不得不面对的问题。有一个在北京的业务(Client 北京 ) 需要连接 (broker 北京 ) &#xff0c;向其中的交换器 exchangeA 发送消息&#xff0c;此时的网络延迟很小&#xff0c;(C…

全球边缘计算大会的十大至暗时刻

来源网友X小缘 ① 背景板文字全球边缘计算大会&#xff0c;被广告公司改为全球边缘计算机大会&#xff0c;因为他觉得少了个机字&#xff1b; ② 明天开会&#xff0c;今天遇到恶劣天气&#xff0c;讲师主持人一整晚滞留外地机场&#xff1b; ③ 视频直播的时候声音通道没开&am…