[Vue3 Ecology] Overview of Vue Router Routing Knowledge

foreword

Vite+Vue3

In web front-end development, routing is a very important part, but what exactly is routing?

  • From the purpose of routing

    Routing refers to displaying different pages to users as the address bar of the browser changes.

  • From the perspective of the implementation principle of routing

    A route is a mapping of URLs to functions. It maps URLs and different parts of the application to specific handlers or controllers.

Routing itself has also gone through different stages of development:

  1. server routing

    Server-side routing is also called back-end routing.

    The server returns different response results according to the URL path accessed by the user. When we click a link in a traditional server-rendered web application, the browser fetches fresh HTML from the server and reloads the entire page.

    For the simplest static resource server, it can be considered that the mapping function of all URLs is a file reading operation. For dynamic resources, the mapping function may be a database read operation, or it may be some data processing and so on.

    • benefit

      Good security and good for SEO (Search Engine Optimization, search engine optimization. It refers to the optimization behavior done to increase the number of pages included in the natural search results of search engines and improve the ranking position)

    • shortcoming

      Increase the pressure on the server, which is not conducive to user experience and code redundancy

    The shortcomings of the official server-side routing make the client-side routing begin to show its prominence.

  2. client routing

    Client routing is also called front-end routing.

    When the user accesses different paths through the client, the routing mapping function uses browser APIs such as History API or hashchangeevents to manage the view that the application should render currently, which basically operates the display and hiding of the DOM.

    • Hash-based implementation

      The early implementation of front-end routing was based on location.hash. The implementation principle is also very simple: listen to the content behind # to initiate an Ajax request to perform partial updates without refreshing the entire page.

      The value of location.hash is the content after # in the URL.

      For example: location.hash = '#me' in https://www.happy.com#me

      hash also has the following characteristics:

      1. The hash value in the URL is only a state of the client, that is to say, when a request is made to the server, the hash part will not be sent.

      2. The change of the hash value will add a record in the browser's access history, so we can control the switching of the hash through the back and forward buttons of the browser.

      3. We can use the hashchange event to monitor URL changes

      There are also two ways to trigger hash changes:

      1.通过a标签,并设置href属性,当用户点击这个标签后,URL就会发生变化,也就会触发hashchange事件了
      
         例如:<a href="#hahha">hahha</a>
      
      2.直接使用js来对location.hash进行赋值,从而改变URL 触发hashchange事件
      
         例如: location.hash = '#hahha'
      
      3.浏览器前进后退改变 URL,触发hashchange事件
      
    • Implementation based on history API

      1. Toggle history state

        Including back(), forword(), go(n) three methods, respectively corresponding to the forward, backward, and jump operations of the browser

        history.go(-2) //后退两次 + 刷新
        history.go(2) //前进两次
        history.back() //后退 (不刷新)
        history.forword() //前进
        

        The back() method loads the previous URL in the history list, if it exists. The effect of calling this method is equivalent to clicking the back button or calling history.go(-1)

        The forward() method loads the next URL in the history list. The effect of calling this method is equivalent to clicking the forward button or calling history.go(1)

      2. Modify history state

        Including pushState() and replaceState(), both of which receive three parameters: stateObj, title, url. They can manipulate browser history without refreshing the page.

        • pushState() adds a new history record
        • replaceState() replaces the current history
        • popstate() event . Used to monitor changes in history

        parameter:

        • state object : A JavaScript object associated with a new history entry created with the pushState() method. Whenever the user navigates to the newly created state, the popstate event is fired and the object can be used in the event
        • Title (title) : general browsers will ignore it, just pass null
        • Address (URL) : A newly added historical record address is required. The browser will not directly load the changed address, but it may try to load the address later. In addition, it should be noted that the incoming URL should have the same origin as the current URL.
      window.onpopstate = function(event) {
        alert("location: " + document.location + ", state: " + JSON.stringify(event.state));
      };
      
      history.pushState({page: 1}, "title 1", "?page=1");
      history.pushState({page: 2}, "title 2", "?page=2");
      history.replaceState({page: 3}, "title 3", "?page=3");
      history.back(); // 弹出 "location: http://example.com/example.html?page=1, state: {"page":1}"
      history.back(); // 弹出 "location: http://example.com/example.html, state: null
      history.go(2);  // 弹出 "location: http://example.com/example.html?page=3, state: {"page":3}
      

**Summary:** Whether it is client-side routing or server-side routing, there are certain application scenarios and scopes of application. SEO优化For web applications that need to provide excellent user experience and dynamic interaction, client-side routing is more suitable; while for websites that need to provide better and website performance, server-side routing is more suitable. But after the emergence of nuxt.jsand next.js, to a large extent, it made up for the problem that traditional client-side routing is not conducive to SEO optimization.

1. Routing in Vue

Vue is a single-page application , and "routing" in a single-page application is performed on the client side. Client-side JavaScript can intercept page jump requests, dynamically obtain new data, and then update the current page without reloading. This often results in a smoother user experience, especially in more "app" scenarios where users typically interact multiple times over a long period of time.

If you only need a simple page route and don't want to introduce a whole route library for this, you can use dynamic components to listen to browser hashchangeevents or use the History API to update the current component.

<script setup>
import { ref, computed } from 'vue'
import A from './A.vue'
import B from './B.vue'
import NotFound from "./NotFound.vue"

const routes = {
    '/': A,
    '/b': B
}

const currentPath = ref(window.location.hash)
window.addEventListener('hashchange', () => {
    currentPath.value = window.location.hash
})
const currentView = computed(() => {
    return routes[currentPath.value.slice(1) || '/'] || NotFound
})
</script>
<template>
    <div>
        <div>
            <a href="#/">A</a>
            <a href="#/b" style="margin-left: 20px">B</a>
        </div>
        <br>
        <Transition name="fade">
            <component :is="currentView" style="margin-top:50px" tag="div"></component>
        </Transition>
    </div>
</template>
<style scoped lang="less">
.fade-enter-from {
    opacity: 0;
}

.fade-enter-active {
    transition: opacity 1s 0.5s ease;
}

.fade-leave-to {
    opacity: 0;
}

.fade-leave-active {
    transition: opacity .5s ease;
}
</style>

If you are doing a project, the routing library is a must. For the Vue project, the official also launched its own routing library Vue Router , which provides expressive, configurable, and convenient routing for Vue.js.

2. Vue Router

insert image description here

Vue Router is the official router for Vue.js. It is deeply integrated with Vue.js core, making it easy to build single-page applications with Vue.js. Features include:

  • Nested route-maps
  • dynamic routing
  • Modular, component-based routing configuration
  • Route parameters, queries, wildcards
  • Show transition effects provided by Vue.js' transition system
  • Detailed Navigation Controls
  • Automatically activate links with CSS classes
  • HTML5 history mode or hash mode
  • Customizable scrolling behavior
  • Correct Encoding of URLs

2.1 Installation and use

2.2.1 Installation

CDN download address: https://unpkg.com/[email protected]/dist/vue-router.global.js

Project integration, install vue-router

# yarn 方式
yarn add vue-router@4

# npm 方式
npm install vue-router@4

package.json after successful installation

insert image description here

2.2.2 Mapping components to routes

With Vue Router installed, all we need to do is map components to routes so it knows where they should be rendered.

  1. Write mapping code (if there are no directories and files, please create them)

    # src/router/index.js
    
    // 引入路由相关方法
    import { createRouter, createWebHistory } from 'vue-router'
    // 引入登录组件 Login
    import Login from '../views/Login.vue'
    // 定义一些路由:每个路由都需要映射到一个组件。路由过多时,根据情况可以分离到单独的文件中
    const routes = [
    	{ path:'/', redirect: '/login' }, // redirect 重定向。这里访问根目录时,跳转到登录页
    	{ path: '/login', name: 'login', component: Login, meta: { title: '登录' } }, // meta 定义路由页的元信息
    	{ 
    		path: '/home',
    		name: 'home',
    		component: () => import('../views/Home.vue'),// 这里组件采用惰性加载,打包时从路由层面拆分代码,可生成一个单独的块 Home.[hash].js
    		children: [ // 嵌套路由:定义子路由信息
    			{
    				name: 'welcome',
                    path: "/welcome",
                    component: () => import ('../views/Welcome.vue'),
                    meta: { title: "欢迎页" }
                },
                {
                    name: 'user',
                    path: "/user",
                    component: () => import ('../views/BaseData/User.vue'),
                    meta: { title: "用户管理" }
                }
    		]
        } 
    ]
    // 创建路由实例并传递 routes 配置
    const router = createRouter({ // 函数参数:路由配置项
    	// 默认提供 history 模式实现。可通过引入 createWebHashHistory 配置 hash 模式。
    	history: createWebHistory(import.meta.env.BASE_URL),
    	// history: createWebHashHistory()
    	// 配置路由
    	routes
    })
    // 导出路由实例
    export default router
    
  2. Mount the routing configuration file to the Vue application

    # src/main.js
    
    import { createApp } from 'vue'
    import App from './App.vue'
    import router from './router' // 默认查找当前路径下的 index.js,同 './router/index'
    
    const app = createApp(App)
    app.use(router)
    app.mount('#app')
    
  3. Use routing in components

    The use of routing in components involves the two concepts of **"routing jump" and "routing exit"**:

    • router-link

      A custom component for creating links. Can make Vue RouterURL changes without reloading the page, handles URL generation and encoding.

    • router-view

      Routing exit, used to display the component corresponding to url (route mapping component), which can be placed in any position.

    <div id="app">
      <h1>Hello App!</h1>
      <p>
        <!--使用 router-link 组件进行导航 -->
        <!--通过传递 `to` 来指定链接 -->
        <!--`<router-link>` 将呈现一个带有正确 `href` 属性的 `<a>` 标签-->
        <router-link to="/">Go to Home</router-link>
        <router-link to="/about">Go to About</router-link>
      </p>
      <!-- 路由出口 -->
      <!-- 路由匹配到的组件将渲染在这里 -->
      <router-view></router-view>
    </div>
    

3. Routing common API

3.1 Attribute components

  • RouterLink is used to render a link component that triggers navigation when the link is clicked
  • RouterView is used to display the user's current route component

3.2 Routing instance function

  • createRouter( options ) creates a Router instance that can be used by Vue applications

    createRouter({
      history: createWebHistory(),
      routes: [
      	{ path: '', name: '', meta: { }, component: CompA, ...}
      	// 其它路由组件配置
      ]
      // 其它选项配置...
    })
    

3.3 history history mode

The history mode used by routers, most should use createWebHistory, but this requires a properly configured server.

If you don't want to configure the server, you can use createWebHashHistory to implement hash-based history records, but this method will not be processed by search engines, and the SEO effect is poor

  • createWebHistory(base?) Creates an HTML5 history. The most common pattern for single page applications.

  • createWebHashHistory(base?) Create a history of hash patterns. No server configuration is required.

    // 基于 https://example.com/folder
    createWebHashHistory() // 给出一个 `https://example.com/folder#` 的 URL
    createWebHashHistory('/folder/') // 给出一个 `https://example.com/folder/#` 的 URL
    
  • createMemoryHistory(base?) Creates a memory-based history, mainly for handling server-side rendering. It starts from a special location that does not exist, which can be replaced with the starting location via router.push or router.replace.

3.4 Routing (navigation) guards

  • onBeforeRouteLeave(to, from, next) { } Triggered when the component at the current location leaves.
  • onBeforeRouteUpdate(to, from, next) {} Triggered when the component at the current location is updated.

Note: All routing guards will be removed when the component is uninstalled.

3.5 Manipulating routing objects in components

  • useRouter returns a router instance. Equivalent to $router used in templates
  • useRoute returns the current route address. Equivalent to using $route in templates. Stores the parameter information passed when the route jumps, such as: params, query, etc.
  • useLink

3.6 router operation function

  • push() programmatically navigates to a new URL by adding a record to the history stack
  • resolve() returns a canonicalized version of a route address . Also include a property that contains any existingbasehref
  • replace() programmatically navigates to a new URL by replacing the current record in the history stack
  • addRoute(parentName, route) Add a new route record as a child of an existing route.

Guess you like

Origin blog.csdn.net/qq_39335404/article/details/131292109