返回文章列表文章索引阅读全文
STARBLOG / 阅读手记
StarBlog前端开发-Vue

StarBlog Blog Development Notes: Frontend Development (2) - Page Routing

Foreword Vue.js uses a virtual DOM to handle single-page applications and then bundles them with Webpack. Through the examples in Chapter 5, you may have noticed that regardless of differences in syntax and writing styles, Vue.js programs are bundled into a single HTML file after packaging, while also introducing a standard JavaScript file. All code written in Vue.js is automatically bundled by Webpack into HTML and JavaScript code that can be parsed by browsers, and the project itself consists of only one page. This means that all users make requests to the server...

曦远 (DealiAxy)约 19 分钟
目录12 个章节

Introduction

Vue.js uses a virtual DOM to handle single pages and then packages them with Webpack. Through the example in the previous article, readers may have noticed that regardless of differences in syntax and coding style, a Vue.js program, once packaged, becomes a single HTML file while also importing a standard JavaScript file.

All the code written in Vue.js is automatically packaged by Webpack into HTML and JavaScript code that can be parsed by browsers, and the project itself consists of only one page. This means that when users send a request to the server to access a page, only one request is made to the server.

In traditional HTML web applications, page navigation causes the page to refresh based on the URL. Even with today's greatly improved internet speeds, such navigation still inevitably results in a "white screen" phenomenon—a temporary blank screen—which is clearly not the desired effect for Vue.js single-page applications. However, the application itself still needs URLs to control pages. In this context, Vue.js provides vue-router to implement page navigation.

This Article

This article provides a preliminary introduction to vue-router. More in-depth usage will be covered in subsequent articles.

  • Introduction to vue-router
  • Two routing modes and their implementation principles
  • Writing three simple Vue pages
  • Installation and configuration of vue-router
  • Testing and verification

About vue-router

The vue-router version used in this project is 3.x, with the official documentation at: https://v3.router.vuejs.org/zh/

Vue Router is the official routing manager for Vue.js. It integrates deeply with Vue.js, allowing developers to easily build single-page applications.

With Vue Router, you can define routes in a component-based manner to achieve flexible page structures and nested view organization.

Its main features include:

  • Flexible Route Definition: Supports nested routes, passing data via URL parameters and query strings, and using wildcards for dynamic matching.
  • Concise Component-Based Configuration: Organically combines routes with components for better project structure organization.
  • Multiple Mode Choices: You can use history mode in modern browsers for a better URL experience; it automatically falls back to hash mode in unsupported environments.
  • Smooth Transition Animations: Integrates with Vue's transition system, enabling seamless page transition animations during navigation.
  • Fine-Grained Navigation Control: Through navigation guards, you can perform logic such as permission checks and data preloading before and after route transitions.
  • Personalized Experience: Includes customizable scroll behavior and automatic CSS class addition to active links, providing users with better interaction and interface feedback.

URL Modes

Vue-router simulates URLs using two modes: hash mode and history mode. (This project uses the default hash mode.)

  • Hash mode is the default mode. It simulates a complete URL using the web page's URL. When the hash value after # changes, it re-fetches the page corresponding to the hash (in Vue.js, the component to be displayed) and displays this content on the page.
  • History mode targets browsers that support the HTML5 history feature. It itself is a stack of browsing history when users access pages, and HTML5 allows manipulation of the content within the history stack.

PS: Regardless of the method used to configure vue-router, Vue.js single-page applications do not refresh the page.

Implementation Differences

  • The hash mode implementation uses history.pushState() to navigate routes; route changes are monitored via the hashchange event.
  • The history mode uses history.pushState and history.replaceState to modify the URL; route changes are monitored via the popstate event, but it cannot capture route changes triggered by history.pushState().

Experience Differences

  • Hash can only change the value after #, while history mode allows freely setting same-origin URLs;
  • Hash can only add string-type data, while history can add various types of data via API;
  • Hash requires no backend configuration and has good compatibility, while history needs to configure index.html for cases where resources cannot be matched;
  • Hash history records only show the previous www.a.com without displaying the hash value, while each record in history mode will be added to the browser history (After Chrome version 102, the full URL of hash mode is also added to the browser history).

Adding Pages

Let's first review our project directory structure:

starblog-admin-ui
├── build
├── config
├── node_modules
├── src
│   ├── assets
│   ├── router
│   ├── components
│   ├── App.vue
│   └── main.js
├── static
├── test
├── README.md
├── index.html
├── package.json
└── yarn.lock

Now I'm going to rename the src/components directory to views

Then add three pages inside it separately:

  • Login.vue
  • Home.vue
  • 404.vue

Home Page

Home.vue Code

<template>
  <el-alert
    title="主页"
    type="success">
  </el-alert>
</template>

<script>
export default {
  name: "Home"
}
</script>

<style scoped>

</style>

Login Page

Then comes Login.vue with

<template>
  <el-alert
    title="登录"
    type="info">
  </el-alert>
</template>

404 Page

There is also 404.vue.

<template>
  <el-alert
    title="未找到"
    type="error">
  </el-alert>
</template>

At this point, the console should show an error, but it's not a big deal. Let's first configure the routing.

Installation and Configuration

When we used vue-cli to create the project earlier, we selected to use vue-router, so it does not need to be installed.

If it is not already included, you will need to manually install it (the vue-router version used in this project is 3.x; note that the latest version is now 4.x, so please choose the corresponding version during installation).

yarn add vue-router

Then, create a new router directory inside the src directory, and within it, create an index.js file with the following code:

import Vue from 'vue'
import Router from 'vue-router'
import Login from "@/views/Login";
import Home from "@/views/Home";
import NotFound from '@/views/404'

Vue.use(Router)

export default new Router({
  mode: 'history',		// This sets the mode for simulating URLs
  routes: [
    {
      path: '/',
      name: 'Home',
      component: Home,
    },
    {
      path: '/Login',
      name: 'Login',
      component: Login
    },
    {
      path: '/404',
      name: 'NotFound',
      component: NotFound
    },
  ]
})

There is a mode setting here, which refers to the two modes for simulating URLs mentioned earlier. If you set it to history, the browser’s address bar will display URLs in this format when navigating between pages:

  • localhost:8080/login
  • localhost:8080/404

If you use the default hash mode, it will look like this:

  • localhost:8080/#/login
  • localhost:8080/#/404

Both are similar, but the history mode looks cleaner. However, to implement it, the browser must support the HTML5 History API, and some backend configuration is also required.

Test Page

Open the following addresses respectively:

  • http://localhost:8080/#/
  • http://localhost:8080/#/Login
  • http://localhost:8080/#/404

Seeing different messages indicates that this step is complete.

Following the usual practice, no screenshots are attached, haha~

Work complete~

_EOF_

StarBlog Blog Development Notes: Frontend Development (2) - Page Routing

本文作者:
程序设计实验室
版权声明:
本博客所有文章除特别声明外,均采用 BY-NC-SA 许可协议。转载请注明出处!

相关文章

StarBlog博客开发笔记:前端开发(3)之SASS与SCSS

前言 本项目需要使用SCSS来编写页面样式。 这里的SASS,是指名为SASS的css预处理器 然后SCSS是一种 CSS-like 语法 对于初学者,SCSS 是完全和 CSS 兼容的,这意味着几乎为零的学习曲线。SCSS语法即是:它只是加了一些功能的 CSS。当你和没经验的开发者一起工作时这很重要:他们可以很快开始编码而不需要首先去学习Sass。 此外,SCSS 还是 易于阅读 的,因为它是有

2024-12-13 · StarBlog前端开发-Vue · 约 1 分钟

StarBlog博客开发笔记:前端开发之导航守卫

路由对象router给我们提供了beforeEach方法,可以在每次路由之前进行一些相关处理,也叫导航守卫,我们这里就通过导航守卫实现一些类似身份认证的辅助功能。 修改router/index.js文件,添加导航守卫,在每次路由时判断用户会话是否过期。如果登录有效且跳转的是登录界面,就直接路由到主页;如果是非登录页面且会话过期,就跳到登录页面要求登录。 代码如下 router.beforeEach

2023-07-14 · StarBlog前端开发-Vue · 约 1 分钟

讨论

共 0 条

良言一句三冬暖,恶语伤人六月寒。

加载评论中…

StarBlog Blog Development Notes: Frontend Development (2) - Page Routing · StarBlog