Home Web Front-end JS Tutorial How to use vue to make front-end routing for single-page applications

How to use vue to make front-end routing for single-page applications

Jun 11, 2018 pm 02:56 PM
spa application vue

This time I will show you how to use vue to make a single-page application front-end routing, and what are the precautions for using vue to make a single-page application front-end routing. The following is a practical case, let's take a look.

Written in front: Usually there are two ways to implement front-end routing in SPA:

  1. window.history

  2. location. hash

The following will introduce how to implement these two methods

1.history

1.Basic introduction to history

The window.history object contains the history of the browser. The window.history object does not need to use the window prefix when writing it. History is a mainstream method for implementing SPA front-end routing. It has several original methods:

  1. history.back() - the same as clicking the back button in the browser

  2. history.forward() - Same as clicking the button forward in the browser

  3. history.go(n) - Accepts an integer as argument, moves to The page specified by this integer, for example, go(1) is equivalent to forward(), go(-1) is equivalent to back(), go(0) is equivalent to refreshing the current page

  4. if The moved position exceeds the boundary of the access history. The above three methods do not report an error, but fail silently

In HTML5, the history object proposes the pushState() method and replaceState() method. , these two methods can be used to add data to the history stack, just as if the url changes (in the past, only the url changed and the history stack would change), so that you can simulate browsing history and forward and backward very well. The current front-end Routing is also implemented based on this principle.

2.history.pushState

pushState(stateObj, title, url) method writes data to the history stack, and its first parameter is to be written Data object (not larger than 640kB), the second parameter is the title of the page, and the third parameter is the url (relative path).

  1. stateObj: A state object related to the specified URL. When the popstate event is triggered, the object will be passed into the callback function. If this object is not needed, null can be filled in here.

  2. title: The title of the new page, but all browsers currently ignore this value, so null can be filled in here.

  3. url: The new URL must be in the same domain as the current page. Your browser's address bar will display this URL.

There are a few things worth noting about pushState:

The pushState method does not trigger a page refresh, but only causes the history object to change, and the address bar will react. The browser will refresh only when events such as forward and backward (back() and forward(), etc.) are triggered

The URL here is restricted by the same-origin policy to prevent malicious scripts from imitating other website URLs for deception user, so when the same-origin policy is violated, an error will be reported

3.history.replaceState

The difference between replaceState(stateObj, title, url) and pushState is that it It is not writing but replacing and modifying the current record in the browsing history. The rest is exactly the same as pushState

4.popstate event

Definition: Whenever the browsing history of the same document ( When the history object) changes, the popstate event will be triggered.

Note: Just calling the pushState method or replaceState method will not trigger this event. It will only be triggered when the user clicks the browser's back button and forward button, or uses JavaScript to call the back, forward, and go methods. In addition, this event only targets the same document. If the switching of browsing history causes different documents to be loaded, this event will not be triggered.

Usage: When using, you can specify a callback function for the popstate event. The parameter of this callback function is an event object, and its state attribute points to the state object provided by the pushState and replaceState methods for the current URL (that is, the first parameter of these two methods).

5.history implements spa front-end routing code

<a class="api a">a.html</a>
<a class="api b">b.html</a>
 // 注册路由
  document.querySelectorAll('.api').forEach(item => {
   item.addEventListener('click', e => {
    e.preventDefault();
    let link = item.textContent;
    if (!!(window.history && history.pushState)) {
     // 支持History API
     window.history.pushState({name: 'api'}, link, link);
    } else {
     // 不支持,可使用一些Polyfill库来实现
    }
   }, false)
  });
  // 监听路由
  window.addEventListener('popstate', e => {
   console.log({
    location: location.href,
    state: e.state
   })
  }, false)
Copy after login

The e.state printed in the popstate listening function is the first one passed in history.pushState() Parameters here are {name: 'api'}

2.Hash

1.Basic introduction to Hash

The url can contain a hash http://localhost:9000/#/a.html

window 对象中有一个事件是 onhashchange,以下几种情况都会触发这个事件:

  1. 直接更改浏览器地址,在最后面增加或改变#hash;

  2. 通过改变location.href或location.hash的值;

  3. 通过触发点击带锚点的链接;

  4. 浏览器前进后退可能导致hash的变化,前提是两个网页地址中的hash值不同。

2.Hash实现spa前端路由代码

  // 注册路由
  document.querySelectorAll('.api').forEach(item => {
   item.addEventListener('click', e => {
    e.preventDefault();
    let link = item.textContent;
    location.hash = link;
   }, false)
  });
  // 监听路由
  window.addEventListener('hashchange', e => {
   console.log({
    location: location.href,
    hash: location.hash
   })
  }, false)
Copy after login

相信看了本文案例你已经掌握了方法,更多精彩请关注php中文网其它相关文章!

推荐阅读:

vue.js怎样部署nginx案例(附代码)

从零开始操作AngularJS实现应用模块化

The above is the detailed content of How to use vue to make front-end routing for single-page applications. For more information, please follow other related articles on the PHP Chinese website!

Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Article

R.E.P.O. Energy Crystals Explained and What They Do (Yellow Crystal)
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. Best Graphic Settings
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. How to Fix Audio if You Can't Hear Anyone
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
WWE 2K25: How To Unlock Everything In MyRise
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

How to reference js file with vue.js How to reference js file with vue.js Apr 07, 2025 pm 11:27 PM

There are three ways to refer to JS files in Vue.js: directly specify the path using the &lt;script&gt; tag;; dynamic import using the mounted() lifecycle hook; and importing through the Vuex state management library.

How to use watch in vue How to use watch in vue Apr 07, 2025 pm 11:36 PM

The watch option in Vue.js allows developers to listen for changes in specific data. When the data changes, watch triggers a callback function to perform update views or other tasks. Its configuration options include immediate, which specifies whether to execute a callback immediately, and deep, which specifies whether to recursively listen to changes to objects or arrays.

How to use bootstrap in vue How to use bootstrap in vue Apr 07, 2025 pm 11:33 PM

Using Bootstrap in Vue.js is divided into five steps: Install Bootstrap. Import Bootstrap in main.js. Use the Bootstrap component directly in the template. Optional: Custom style. Optional: Use plug-ins.

What does it mean to lazy load vue? What does it mean to lazy load vue? Apr 07, 2025 pm 11:54 PM

In Vue.js, lazy loading allows components or resources to be loaded dynamically as needed, reducing initial page loading time and improving performance. The specific implementation method includes using &lt;keep-alive&gt; and &lt;component is&gt; components. It should be noted that lazy loading can cause FOUC (splash screen) issues and should be used only for components that need lazy loading to avoid unnecessary performance overhead.

How to add functions to buttons for vue How to add functions to buttons for vue Apr 08, 2025 am 08:51 AM

You can add a function to the Vue button by binding the button in the HTML template to a method. Define the method and write function logic in the Vue instance.

Vue realizes marquee/text scrolling effect Vue realizes marquee/text scrolling effect Apr 07, 2025 pm 10:51 PM

Implement marquee/text scrolling effects in Vue, using CSS animations or third-party libraries. This article introduces how to use CSS animation: create scroll text and wrap text with &lt;div&gt;. Define CSS animations and set overflow: hidden, width, and animation. Define keyframes, set transform: translateX() at the beginning and end of the animation. Adjust animation properties such as duration, scroll speed, and direction.

How to query the version of vue How to query the version of vue Apr 07, 2025 pm 11:24 PM

You can query the Vue version by using Vue Devtools to view the Vue tab in the browser's console. Use npm to run the "npm list -g vue" command. Find the Vue item in the "dependencies" object of the package.json file. For Vue CLI projects, run the "vue --version" command. Check the version information in the &lt;script&gt; tag in the HTML file that refers to the Vue file.

How to return to previous page by vue How to return to previous page by vue Apr 07, 2025 pm 11:30 PM

Vue.js has four methods to return to the previous page: $router.go(-1)$router.back() uses &lt;router-link to=&quot;/&quot; component window.history.back(), and the method selection depends on the scene.

See all articles