search
HomeWeb Front-endJS TutorialVue mobile terminal routing switching case analysis

This time I will bring you an analysis of the vue mobile routing switching case. What are the precautions for vue mobile routing switching? The following is a practical case, let's take a look.

The most important of them are the following two problems:

Switching of the browser navigation bar


When sliding to switch on IOS, there will be two page transitions. Field animation, a switch when it slides, and then triggers the transition animation we set.


Except for the above two questions, the rest of the operations can be set within the page and are basically controllable. Mainly to solve the above two problems.

You can see the actual written effect: Online DEMO

1. Switching the browser navigation bar

By recording history To compare and judge whether to go forward or backward

The following example


A page-> B page-> C page


If I go from page A to page B and then to page C, there will be 3 historical records

We use an array to represent: ['/a', '/b', '/c']

Then when I click the back button on the browser navigation bar, I will return to page B.

At this time, I only need to determine whether page B exists. If it exists, it proves that I clicked the back button. .

Then as long as I go back, I can click the browser's forward button. How to judge whether it is moving forward at this time?

We can do this.

When we go back to page B, doesn’t the history record still save the three paths ['/a', '/b', '/c']?

We can delete page B The following path is now ['/a', '/b'];

If we go back to page A, then the path we save is ['/a']

As long as we click For the forward button, let's look for it in the saved path. If we can't find the path, then the forward judgment will be completed.

The above is a normal situation.

But what if we enter some pages repeatedly.

Just like the following situation

A page-> B page-> C page-> B page-> C page

Now we take 5 steps and reach the second C page, then we take a step back and reach the B page


The problem comes out at this time, we delete the first B page The path is still to delete the path after the second B page

Let's first try to delete the path of the second B page, then the path we still save is: ['/a', '/b', '/c', '/b'].


1. At this time, we operate according to the logic of the normal situation above.


I click forward, and then I search in the saved path. If I can’t find it, even if I can’t find it, To move forward, to find proof is to move backward.


The result is obvious, we have found the first C page, then even if we go back, but in fact when I click, we go forward


2. Then let’s try Now delete the path after the first B page, then the saved path is: ['/a', '/b'],


Then when I click the back button, he will actually Entering the C page, we can see the following flow chart

At this time, if we click the back button here, we will go to the C page, but the saved path is `'/c' ` has been deleted by me, so the judgment is to move forward.

1. Would it be better if we filtered duplicate page paths? In fact, it is the same.


If we have 5 page paths, 2 duplicates are filtered out Yes, there are only 3 page paths.


Then I can’t find it when I return to the fourth path. Then the next two pages will be counted as forward.


So from the current point of view, the best way is to record every page, but make each page different


Then we can put it in the url Put a random

string

code implementation on it:


// 当没有key的时候会进入两次 beforeEach,我们只需保存带key的就行
const updateNavigations = (to) => {
 if (to.query[pathKey]) {
  store.commit('UPDATE_NAVIGATIONS', {path: to.fullPath})
 }
}

router.beforeEach((to, from, next) => {
 let toIndex = store.state.navigations.findIndex(path => path === to.fullPath)
 if (toIndex >= 0) { // 存在该路径
  let len = store.state.navigations.length-1
  if (toIndex === len) { // 当前路径是最后一条,证明是同一个页面
   console.log('refresh') 
  } else { // 后退
   store.commit('UPDATE_ROUTER_DIRECTION', { routerDirection: 'back' }) // 后退标志
   store.commit('DELETE_NAVIGATION', { index: toIndex }) // 删除当前路径后面的路径
  }
 }else{ // 不存在该路径
  store.commit('UPDATE_ROUTER_DIRECTION', { routerDirection: 'forward' }) // 前进标志
  updateNavigations(to) // 保存该连接
 }

 const query = { ...to.query }
 // 存在就直接next, 防止死循环
 if (!query['APP_KEY']) { // 不存在添加key ,再次 next
  query['APP_KEY'] = Math.random().toString(16).substring(2)
  next({ path: to.path, query})
 }else{
  next()
 }
})


We will use the above code You can add a random string of APP_KEY to the URL, so that even if the same page is in the path we save, it will actually be different. The logic can be executed normally


The above basically solves the problem of the browser navigation bar

2. Sliding switching on IOS

On the IOS web page, you can slide left and right to switch, even if you don't do a transition animation.


A problem will arise at this time.

Still ABC page

A -> B -> C

When we reach the C page and then slide to the left, finish sliding him Just enter the B page, but at this time it will still enter our beforeEach hook function and execute our above logic.


That will trigger our transition animation. You will find that two switches are performed.

So I found a method on the Internet to fix ios and slide left to execute the animation again#2259

The code is like this


let touchEndTime = Date.now()

window.addEventListener('touchend', () => {
 touchEndTime = Date.now()
})

router.beforeEach((to, from, next) => {
 if ((Date.now() - touchEndTime) < 377) { // ios滑动切换
  store.commit(&#39;UPDATE_ROUTER_DIRECTION&#39;, { routerDirection: &#39;&#39; })
 }
})


The above is also easy to understand, that is, we get the moment when the finger finally leaves the screen, and then compare it in beforeEach.
The difference between the last moment when the finger leaves the screen and our own transition in beforeEach Less than 337, even if it is the sliding switching of IOS

, that will solve the sliding switching problem of IOS.

But when IOS slides right to switch, it cannot monitor the moment when the finger leaves the screen (I don’t know what the ghost is), so IOS slides right to switch and cannot be judged as above.

I haven’t found a solution to this. For the time being, I can only solve the switch of left swiping back in IOS.

Basically, the two most troublesome points are the above two points. The rest can be set by listening to events, which is not difficult

Online DEMO Demonstration

I believe you have mastered the method after reading the case in this article. For more exciting information, please pay attention to other related articles on the php Chinese website!

Recommended reading:

Detailed explanation of how to use jQuery class name selector (.class)

vue dynamic binding component child and parent components Detailed explanation of the steps to implement multi-form verification

#

The above is the detailed content of Vue mobile terminal routing switching case analysis. For more information, please follow other related articles on the PHP Chinese website!

Statement
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
Building a Multi-Tenant SaaS Application with Next.js (Backend Integration)Building a Multi-Tenant SaaS Application with Next.js (Backend Integration)Apr 11, 2025 am 08:23 AM

I built a functional multi-tenant SaaS application (an EdTech app) with your everyday tech tool and you can do the same. First, what’s a multi-tenant SaaS application? Multi-tenant SaaS applications let you serve multiple customers from a sing

How to Build a Multi-Tenant SaaS Application with Next.js (Frontend Integration)How to Build a Multi-Tenant SaaS Application with Next.js (Frontend Integration)Apr 11, 2025 am 08:22 AM

This article demonstrates frontend integration with a backend secured by Permit, building a functional EdTech SaaS application using Next.js. The frontend fetches user permissions to control UI visibility and ensures API requests adhere to role-base

JavaScript: Exploring the Versatility of a Web LanguageJavaScript: Exploring the Versatility of a Web LanguageApr 11, 2025 am 12:01 AM

JavaScript is the core language of modern web development and is widely used for its diversity and flexibility. 1) Front-end development: build dynamic web pages and single-page applications through DOM operations and modern frameworks (such as React, Vue.js, Angular). 2) Server-side development: Node.js uses a non-blocking I/O model to handle high concurrency and real-time applications. 3) Mobile and desktop application development: cross-platform development is realized through ReactNative and Electron to improve development efficiency.

The Evolution of JavaScript: Current Trends and Future ProspectsThe Evolution of JavaScript: Current Trends and Future ProspectsApr 10, 2025 am 09:33 AM

The latest trends in JavaScript include the rise of TypeScript, the popularity of modern frameworks and libraries, and the application of WebAssembly. Future prospects cover more powerful type systems, the development of server-side JavaScript, the expansion of artificial intelligence and machine learning, and the potential of IoT and edge computing.

Demystifying JavaScript: What It Does and Why It MattersDemystifying JavaScript: What It Does and Why It MattersApr 09, 2025 am 12:07 AM

JavaScript is the cornerstone of modern web development, and its main functions include event-driven programming, dynamic content generation and asynchronous programming. 1) Event-driven programming allows web pages to change dynamically according to user operations. 2) Dynamic content generation allows page content to be adjusted according to conditions. 3) Asynchronous programming ensures that the user interface is not blocked. JavaScript is widely used in web interaction, single-page application and server-side development, greatly improving the flexibility of user experience and cross-platform development.

Is Python or JavaScript better?Is Python or JavaScript better?Apr 06, 2025 am 12:14 AM

Python is more suitable for data science and machine learning, while JavaScript is more suitable for front-end and full-stack development. 1. Python is known for its concise syntax and rich library ecosystem, and is suitable for data analysis and web development. 2. JavaScript is the core of front-end development. Node.js supports server-side programming and is suitable for full-stack development.

How do I install JavaScript?How do I install JavaScript?Apr 05, 2025 am 12:16 AM

JavaScript does not require installation because it is already built into modern browsers. You just need a text editor and a browser to get started. 1) In the browser environment, run it by embedding the HTML file through tags. 2) In the Node.js environment, after downloading and installing Node.js, run the JavaScript file through the command line.

How to send notifications before a task starts in Quartz?How to send notifications before a task starts in Quartz?Apr 04, 2025 pm 09:24 PM

How to send task notifications in Quartz In advance When using the Quartz timer to schedule a task, the execution time of the task is set by the cron expression. Now...

See all articles

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 agoBy尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. Best Graphic Settings
3 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. How to Fix Audio if You Can't Hear Anyone
3 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
WWE 2K25: How To Unlock Everything In MyRise
3 weeks agoBy尊渡假赌尊渡假赌尊渡假赌

Hot Tools

DVWA

DVWA

Damn Vulnerable Web App (DVWA) is a PHP/MySQL web application that is very vulnerable. Its main goals are to be an aid for security professionals to test their skills and tools in a legal environment, to help web developers better understand the process of securing web applications, and to help teachers/students teach/learn in a classroom environment Web application security. The goal of DVWA is to practice some of the most common web vulnerabilities through a simple and straightforward interface, with varying degrees of difficulty. Please note that this software

SAP NetWeaver Server Adapter for Eclipse

SAP NetWeaver Server Adapter for Eclipse

Integrate Eclipse with SAP NetWeaver application server.

EditPlus Chinese cracked version

EditPlus Chinese cracked version

Small size, syntax highlighting, does not support code prompt function

Dreamweaver Mac version

Dreamweaver Mac version

Visual web development tools

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment