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

这篇具有很好参考价值的文章主要介绍了前端vue2、vue3去掉url路由“ # ”号——nginx配置。希望对大家有所帮助。如果存在错误或未考虑完全的地方,请大家不吝赐教,您也可以点击"举报违法"按钮提交疑问。


前端vue2、vue3去掉url路由“ # ”号——nginx配置,JavaScript专栏,web站点,前端,nginx,javascript,vue2,vue3,html hash,html history

⭐前言

大家好,我是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、vue3去掉url路由“ # ”号——nginx配置,JavaScript专栏,web站点,前端,nginx,javascript,vue2,vue3,html hash,html history

💖在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 没有 # 号

前端vue2、vue3去掉url路由“ # ”号——nginx配置,JavaScript专栏,web站点,前端,nginx,javascript,vue2,vue3,html hash,html history

💖在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启动打开
检查绝对路径
前端vue2、vue3去掉url路由“ # ”号——nginx配置,JavaScript专栏,web站点,前端,nginx,javascript,vue2,vue3,html hash,html history
检查http-server可以运行vue而且没有#号
前端vue2、vue3去掉url路由“ # ”号——nginx配置,JavaScript专栏,web站点,前端,nginx,javascript,vue2,vue3,html hash,html history
前端vue2、vue3去掉url路由“ # ”号——nginx配置,JavaScript专栏,web站点,前端,nginx,javascript,vue2,vue3,html hash,html history

⭐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/
前端vue2、vue3去掉url路由“ # ”号——nginx配置,JavaScript专栏,web站点,前端,nginx,javascript,vue2,vue3,html hash,html history

⭐结束

本文分享到这结束,如有错误或者不足之处欢迎指出!
前端vue2、vue3去掉url路由“ # ”号——nginx配置,JavaScript专栏,web站点,前端,nginx,javascript,vue2,vue3,html hash,html history

👍 点赞,是我创作的动力!
⭐️ 收藏,是我努力的方向!
✏️ 评论,是我进步的财富!
💖 感谢你的阅读!文章来源地址https://www.toymoban.com/news/detail-675421.html

到了这里,关于前端vue2、vue3去掉url路由“ # ”号——nginx配置的文章就介绍完了。如果您还想了解更多内容,请在右上角搜索TOY模板网以前的文章或继续浏览下面的相关文章,希望大家以后多多支持TOY模板网!

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处: 如若内容造成侵权/违法违规/事实不符,请点击违法举报进行投诉反馈,一经查实,立即删除!

领支付宝红包 赞助服务器费用

相关文章

  • 记:vite3+vue3+axios前端项目跨域问题解决【前端和服务器nginx配置】

    前言:什么是跨域,网上一搜一大把,所以这里直接跳过,直入主题。 处理方式:不通过后端处理跨域,通过前端+服务器nginx处理。 1.前端涉及处理跨域的必要配置(开发环境、生产环境):vite3、vue3、axios 2.服务器涉及处理跨域的配置(生产环境):nginx【主要用到其配置

    2024年02月01日
    浏览(19)
  • nginx代理去掉URl前缀

    今天接到一个配置nginx的需求是:需要访问某个域名时,nginx可以去掉前缀去代理访问到后端 正常配置情况下: 在nginx配置文件中中设置了 location /prod-api/api 时 浏览器访问 /prod-api/api 反向代理到后端服务后,后端服务接收到的url地址实际还是 /prod-api/api 需要实现的功能需求:

    2024年02月10日
    浏览(12)
  • Vue2向Vue3过度核心技术路由

    1.思考 单页面应用程序,之所以开发效率高,性能好,用户体验好 最大的原因就是: 页面按需更新 比如当点击【发现音乐】和【关注】时, 只是更新下面部分内容 ,对于头部是不更新的 要按需更新,首先就需要明确: 访问路径 和 组件 的对应关系! 访问路径 和 组件的对

    2024年02月11日
    浏览(16)
  • 【前端面经】Vue3和Vue2的区别

    Vue是一种非常流行的JavaScript框架,因其易用性和灵活性在开发人员中备受欢迎。Vue2是Vue框架的上一个重要版本,于2016年发布。但是,Vue3是最新版本的Vue框架,于2020年正式发布并带来了一些重大变化。本文将探讨Vue3和Vue2之间的主要区别。 Vue3的一个显着优势是其更小的代码

    2024年02月02日
    浏览(51)
  • 前端(四)——vue.js、vue、vue2、vue3

    😊博主:小猫娃来啦 😊文章核心: vue.js、vue、vue2、vue3从全局到局部 Vue.js是一款流行的JavaScript框架 vue,vue2,vue3都是vue.js的不同版本。 Vue:Vue.js的第一个版本,也称为Vue 1.x。它于2014年首次发布,并获得了广泛的应用和认可。 Vue2:Vue.js的第二个版本,也称为Vue 2.x。它在Vu

    2024年02月12日
    浏览(15)
  • uniapp使用addInterceptor路由拦截(vue2 OR vue3)

    说明 初始版本方法,可能因为能力原因存在不足,请见谅,有问题评论区~~ 主要通过 uni.addInterceptor api进行路由拦截 目前小程序上面对于uniapp提供的路由跳转方式可以实现拦截,自带的返回按钮,底部tabbar切换无法拦截他们的跳转,但是可以监听到to和from h5支持路由全部拦截

    2024年02月09日
    浏览(11)
  • 【前端Vue】Vue3+Pinia小兔鲜电商项目第4篇:静态结构搭建和路由配置,1. 准备分类组件【附代码文档】

    Vue3+ElementPlus+Pinia开发小兔鲜电商项目完整教程(附代码资料)主要内容讲述:认识Vue3,使用create-vue搭建Vue3项目1. Vue3组合式API体验,2. Vue3更多的优势,1. 认识create-vue,2. 使用create-vue创建项目,1. setup选项的写法和执行时机,2. setup中写代码的特点。什么是pinia,创建空Vue项目并安装

    2024年04月11日
    浏览(17)
  • 从Vue2到Vue3, 一键升级前端开发技能

    本文的目的,是为了让已经有 Vue2 开发经验的   人   ,快速掌握 Vue3 的写法。 因此,   本篇假定你已经掌握 Vue 的核心内容   ,只为你介绍编写 Vue3 代码,需要了解的内容。 首先,Vue3 新增了一个叫做组合式 api 的东西,英文名叫 Composition API 。因此 Vue3 的  script  现在支

    2024年02月08日
    浏览(18)
  • 关于前端框架vue2升级为vue3的相关说明

    一些框架需要升级 当前(202306) Vue 的最新稳定版本是 v3.3.4 。Vue 框架升级为最新的3.0版本,涉及的相关依赖变更有: 前提条件:已安装 16.0 或更高版本的Node.js(摘) 必须的变更:核心库vue@23、路由vue-router@34、状态管理vuex@34 构建工具链: Vue CLI Vite(摘) 状态管理: Vuex Pi

    2024年02月15日
    浏览(14)
  • 【Vue3/Vue2】判断设备是移动端还是pc端跳转不同路由router

          APP文件中写入js代码 1、首先,通过 isMobile() 函数判断用户的设备类型。该函数使用正则表达式匹配 navigator.userAgent 字符串,以确定用户是在移动设备上访问网页还是在桌面设备上访问网页 2、然后,在 onMounted() 钩子函数中,根据当前的路由路径来判断是否需要进行重定

    2024年01月16日
    浏览(24)

觉得文章有用就打赏一下文章作者

支付宝扫一扫打赏

博客赞助

微信扫一扫打赏

请作者喝杯咖啡吧~博客赞助

支付宝扫一扫领取红包,优惠每天领

二维码1

领取红包

二维码2

领红包