返回文章列表文章索引阅读全文
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博客开发笔记:前端开发(8)之vuex与状态管理

状态管理 在很多应用场景下,我们需要在组件之间共享状态,比如我们的左侧导航栏需要收缩和展开的功能,收缩状态时宽度很小,只显示菜单图标,因为导航菜单栏收缩之后宽度变了,所以右侧的主内容区域要占用导航栏收缩的空间,主内容区域宽度也要根据导航栏的收缩状态做变更,而导航栏和主内容区域是两个不同的组件,而非父子组件之间不支持状态传递,所以组件之间的状态共享问题发生了。 之前我写flutter的时候,响应式设

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

讨论

共 0 条

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

加载评论中…