


How to configure the front-end routing of vue single-page application
This time I will show you how to configure the front-end routing of vue single-page application. What are the precautions for configuring the front-end routing of vue single-page application. 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:
window.history
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:
history.back() - the same as clicking the back button in the browser
history.forward() - Same as clicking the button forward in the browser
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
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, history object proposes 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 change history stack will change), so that you can well simulate browsing history and progress. After retreating, 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).
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.
title: The title of the new page, but all browsers currently ignore this value, so null can be filled in here.
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. Only the user clicks the browser's back button and forward button, or uses JavaScript to call the back, forward, and go methods. It will be triggered only when. 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 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)
The e.state printed in the popstate listening function is the first one passed in history.pushState() Parameters, here is {name: 'api'}
二.Hash
1.Hash基本介绍
url 中可以带有一个 hash http://localhost:9000/#/a.html
window 对象中有一个事件是 onhashchange,以下几种情况都会触发这个事件:
直接更改浏览器地址,在最后面增加或改变#hash;
通过改变location.href或location.hash的值;
通过触发点击带锚点的链接;
浏览器前进后退可能导致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)
相信看了本文案例你已经掌握了方法,更多精彩请关注php中文网其它相关文章!
推荐阅读:
The above is the detailed content of How to configure the front-end routing of vue single-page application. For more information, please follow other related articles on the PHP Chinese website!

Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

Video Face Swap
Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Hot Tools

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

Hot Topics

PHP and Vue: a perfect pairing of front-end development tools. In today's era of rapid development of the Internet, front-end development has become increasingly important. As users have higher and higher requirements for the experience of websites and applications, front-end developers need to use more efficient and flexible tools to create responsive and interactive interfaces. As two important technologies in the field of front-end development, PHP and Vue.js can be regarded as perfect tools when paired together. This article will explore the combination of PHP and Vue, as well as detailed code examples to help readers better understand and apply these two

Apache Camel is an Enterprise Service Bus (ESB)-based integration framework that can easily integrate disparate applications, services, and data sources to automate complex business processes. ApacheCamel uses route-based configuration to easily define and manage integration processes. Key features of ApacheCamel include: Flexibility: ApacheCamel can be easily integrated with a variety of applications, services, and data sources. It supports multiple protocols, including HTTP, JMS, SOAP, FTP, etc. Efficiency: ApacheCamel is very efficient, it can handle a large number of messages. It uses an asynchronous messaging mechanism, which improves performance. Expandable

As a C# developer, our development work usually includes front-end and back-end development. As technology develops and the complexity of projects increases, the collaborative development of front-end and back-end has become more and more important and complex. This article will share some front-end and back-end collaborative development techniques to help C# developers complete development work more efficiently. After determining the interface specifications, collaborative development of the front-end and back-end is inseparable from the interaction of API interfaces. To ensure the smooth progress of front-end and back-end collaborative development, the most important thing is to define good interface specifications. Interface specification involves the name of the interface

Django is a web application framework written in Python that emphasizes rapid development and clean methods. Although Django is a web framework, to answer the question whether Django is a front-end or a back-end, you need to have a deep understanding of the concepts of front-end and back-end. The front end refers to the interface that users directly interact with, and the back end refers to server-side programs. They interact with data through the HTTP protocol. When the front-end and back-end are separated, the front-end and back-end programs can be developed independently to implement business logic and interactive effects respectively, and data exchange.

As a fast and efficient programming language, Go language is widely popular in the field of back-end development. However, few people associate Go language with front-end development. In fact, using Go language for front-end development can not only improve efficiency, but also bring new horizons to developers. This article will explore the possibility of using the Go language for front-end development and provide specific code examples to help readers better understand this area. In traditional front-end development, JavaScript, HTML, and CSS are often used to build user interfaces

In front-end development interviews, common questions cover a wide range of topics, including HTML/CSS basics, JavaScript basics, frameworks and libraries, project experience, algorithms and data structures, performance optimization, cross-domain requests, front-end engineering, design patterns, and new technologies and trends. . Interviewer questions are designed to assess the candidate's technical skills, project experience, and understanding of industry trends. Therefore, candidates should be fully prepared in these areas to demonstrate their abilities and expertise.

Django: A magical framework that can handle both front-end and back-end development! Django is an efficient and scalable web application framework. It is able to support multiple web development models, including MVC and MTV, and can easily develop high-quality web applications. Django not only supports back-end development, but can also quickly build front-end interfaces and achieve flexible view display through template language. Django combines front-end development and back-end development into a seamless integration, so developers don’t have to specialize in learning

Combination of Golang and front-end technology: To explore how Golang plays a role in the front-end field, specific code examples are needed. With the rapid development of the Internet and mobile applications, front-end technology has become increasingly important. In this field, Golang, as a powerful back-end programming language, can also play an important role. This article will explore how Golang is combined with front-end technology and demonstrate its potential in the front-end field through specific code examples. The role of Golang in the front-end field is as an efficient, concise and easy-to-learn
