Table of Contents
场景三: 缓存的原因(2019.4.15)
Home Web Front-end Vue.js In-depth analysis of the white screen problem of routing switching in Vue (with code)

In-depth analysis of the white screen problem of routing switching in Vue (with code)

Aug 24, 2021 am 10:54 AM
vue.js

In the previous article "A brief analysis of the two-way binding principle of complie data in vue (detailed code explanation)", we learned about the two-way binding principle of complie data in vue. The following article will help you understand the problem of white screen when routing in Vue. Let’s take a look.

In-depth analysis of the white screen problem of routing switching in Vue (with code)

Regarding the white screen of vue routing switching, in fact, I have never encountered it during the development process.

A friend of mine encountered this problem and asked me how to solve it. I fainted. I have never encountered such a problem. How can I solve it? .

In fact, I encountered it once.

The following content was modified on 2019-07-25.

Server deployment configuration problem

The white screen caused by this problem is as follows:

The homepage can be browsed normally, but---- --Passing $router.push('/home')jumps to the page normally, and then refreshes to get a white screen or 404

I didn’t want to include this problem and solution in the article, because the official website The correct deployment posture has been provided (check the documentation for the routing mode of Vue), mainly for the HTML5 History mode:

const router = new VueRouter({
  mode: 'history',
  routes: [...]
})
Copy after login

dev## There is no problem with # and build, this is for sure, so the problem lies in the server configuration. Taking nginx as an example, the correct configuration is as follows:

location / {
  ....
  try_files $uri $uri/ /index.html; #重点
}
Copy after login

Apache, native Node.js, IIS, Caddy, Firebase Host

Please see

vur-routerBackend configuration example

Address: https://router.vuejs.org/zh/guide/essentials/history-mode.html#Backend configuration Example

The above content was modified on 2019-07-25.

The following content was modified on 2019-04-23.

If you are using

scaffolding initialization environment, you can skip this part. If you configure webpack yourself, you can check and make sure you have done the following configuration

devServer: {
  ...
  contentBase: false, //必须
  historyApiFallback: true, //必须
  ...
},
entry: {
    app: ['./src/main.js'],
    vendors: ['vue', 'vue-router'] //注意这里
},
plugins: [
  ....
  new HtmlWebpackPlugin({
    ...
    chunks: ['vendors', 'app'], //注意这里,这里的chunks 要包含入口的 entry
  })
]
Copy after login

The above content was modified on 2019-04-23.

Scenario 1: IE9 (compatibility issue)

Strictly speaking, it is not a white screen issue. It should be said to be a compatibility issue. It simply does not support it, an error is reported, and rendering cannot be done. caused by execution. The solution is

npm i babel-polyfill -D
Copy after login

and then import it into main.js at the entrance. It’s as simple as

import "babel-polyfill";
Copy after login

or


//webpack
entry: {
      app: ['babel-polyfill','./src/main.js'],
      vendors: ['vue', 'vue-router']
},
Copy after login

. The following content is in 2019 -04-23 modified.

If it is really a

js compatibility issue, then it really just needs to introduce babel-polyfill or add it at the webpack entrancebabel-polyfillWill the problem be solved? In fact, not necessarily. This depends on the usage of the project. babel-polyfill is not a panacea. So how to troubleshoot compatibility issues (if it is really a compatibility issue). Because we are debugging directly on the phone, some errors will not be so easily obvious. This is how I debugged it. (For reference only!)

<template>
  <div>
    <!-- 错误直接显示在这里. 不用 alert() ,console.log()  -->
    {{error}} ...
    <!-- other element -->
  </div>
</template>
<script>
  export default{
    data{
      return {
        error:&#39;&#39;
      }
    },
    moundted:{
      try{
        //一些请求数据的方法
      }catch(e){
        //这里抛出异常
        this.error = e
      }
    }
  }
</script>
Copy after login

What I want to say here is that there are some compatibility issues that

bable-polyfill cannot solve. For example, URLSearchParams

let data = new URLSearchParams();
for (var key in params) {
  data.append(key, params[key]);
}
Copy after login

will definitely report

URLSearchParams is not undefined. Then, the error will only occur on some low-end models and on some occasional occasions. Increase the size Error troubleshooting.

The following can be solved

URLSearchParams is not undefined

//# console
npm i url-search-params-polyfill

//# mian.js
import &#39;url-search-params-polyfill&#39;;
Copy after login

The above content was modified on 2019-04-23.

Scenario 2: As shown below

Some people say that this problem occurs on iPhone 5s or 6s. It is definitely not a bug of the phone. So I recreated the scene, and it really had nothing to do with the equipment

In-depth analysis of the white screen problem of routing switching in Vue (with code)

So this really had nothing to do with the equipment. Knowing the problem, of course there are many solutions

Option 1: Violent and stupid type

//路由跳转前滚动条清零
document.body.scrollTop = document.documentElement.scrollTop = 0;
this.$router.push({ path: "/a/b/c" });
Copy after login

Option 2: Feasible but not optional

//给router 加一个监听,一旦改变,执行清零,然后再跳转
let routers = new Router({.....})
routers.beforeEach(function (to, from, next) {
    ......
    document.body.scrollTop = document.documentElement.scrollTop = 0
    next()
})
Copy after login

Although it is feasible, it feels a bit stupid to do it. Because there is a better way of writing, this way of writing is more elegant

Option 3: Best Type

In fact, the official has provided the ability to control the scroll position when the route is switched. The way.

scrollBehavior

is used as follows:

const router = new VueRouter({
  routes: [...],
  scrollBehavior (to, from, savedPosition) {
    // return 期望滚动到哪个的位置 { x: number, y: number } |  { selector: string } |
  }
})
Copy after login

scrollBehavior method receives to and from routing objects . The third parameter savedPosition is available if and only if popstate navigation (triggered by the browser's forward/back buttons).

So if you want to solve the problem of white screen, what can you do

const router = new VueRouter({
  routes: [...],
  scrollBehavior (to, from, savedPosition) {
    return savedPosition || { x: 0, y: 0 }
  }
})
Copy after login

That is to say, when the user clicks return or forward, the page will scroll to the previous position, (WeChat Moments The article is like this. Go back after reading half of it, then come in and continue reading from the previous position)

If it is a new

page that is mounted, it will be reset. is 0.

完美的解决了这个问题。

但是这也是个问题,框架为什么不默认呢,假如自定义的时候可以overwirte

场景三: 缓存的原因(2019.4.15)

我们根据版本号(或者hash)去控制缓存问题,当我们发布新版本,会发现html里面引用的版本号却是旧的版本号 ,这种情况是入口index.html文件被缓存了,很多时候我们设置禁止html文件被缓存,但依然会出现被缓存的情况。比如在头部加

<meta http-equiv="Expires" content="0" />
<meta http-equiv="Pragma" content="no-cache" />
<meta http-equiv="Cache-control" content="no-cache" />
<meta http-equiv="Cache" content="no-cache" />
Copy after login

仍然解决不了问题,关于web的缓存策略,推荐这篇文章:Http缓存机制

一旦index.html被缓存了,之后我们使用了全量更新,也就是每次发版本之前会干掉之前的jscss文件,那么被缓存的index.html会无法加载之前旧的js,css还有一些其他的静态资源文件,而新的jscss则不会被加载,那么白屏就诞生了。

这个时候我们就要配合服务端来解决index.html的缓存问题

解决缓存的问题请转到这里:Vue index.html入口缓存问题

[完]

推荐学习:vue.js教程

The above is the detailed content of In-depth analysis of the white screen problem of routing switching in Vue (with code). 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)
2 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
Repo: How To Revive Teammates
4 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
Hello Kitty Island Adventure: How To Get Giant Seeds
4 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)

Use vue-cropper to crop images in the vue project Use vue-cropper to crop images in the vue project Oct 31, 2022 pm 07:16 PM

How to crop images in vue project? The following article will introduce to you how to use vue-cropper to crop images. I hope it will be helpful to you!

Let's talk in depth about reactive() in vue3 Let's talk in depth about reactive() in vue3 Jan 06, 2023 pm 09:21 PM

Foreword: In the development of vue3, reactive provides a method to implement responsive data. This is a frequently used API in daily development. In this article, the author will explore its internal operating mechanism.

Practical combat: Develop a plug-in in vscode that supports vue files to jump to definitions Practical combat: Develop a plug-in in vscode that supports vue files to jump to definitions Nov 16, 2022 pm 08:43 PM

vscode itself supports Vue file components to jump to definitions, but the support is very weak. Under the configuration of vue-cli, we can write many flexible usages, which can improve our production efficiency. But it is these flexible writing methods that prevent the functions provided by vscode itself from supporting jumping to file definitions. In order to be compatible with these flexible writing methods and improve work efficiency, I wrote a vscode plug-in that supports Vue files to jump to definitions.

Detailed graphic explanation of how to integrate the Ace code editor in a Vue project Detailed graphic explanation of how to integrate the Ace code editor in a Vue project Apr 24, 2023 am 10:52 AM

Ace is an embeddable code editor written in JavaScript. It matches the functionality and performance of native editors like Sublime, Vim, and TextMate. It can be easily embedded into any web page and JavaScript application. Ace is maintained as the main editor for the Cloud9 IDE and is the successor to the Mozilla Skywriter (Bespin) project.

Explore how to write unit tests in Vue3 Explore how to write unit tests in Vue3 Apr 25, 2023 pm 07:41 PM

Vue.js has become a very popular framework in front-end development today. As Vue.js continues to evolve, unit testing is becoming more and more important. Today we’ll explore how to write unit tests in Vue.js 3 and provide some best practices and common problems and solutions.

What is the difference between componentization and modularization in vue What is the difference between componentization and modularization in vue Dec 15, 2022 pm 12:54 PM

The difference between componentization and modularization: Modularization is divided from the perspective of code logic; it facilitates code layered development and ensures that the functions of each functional module are consistent. Componentization is planning from the perspective of UI interface; componentization of the front end facilitates the reuse of UI components.

A brief analysis of how to handle exceptions in Vue3 dynamic components A brief analysis of how to handle exceptions in Vue3 dynamic components Dec 02, 2022 pm 09:11 PM

How to handle exceptions in Vue3 dynamic components? The following article will talk about Vue3 dynamic component exception handling methods. I hope it will be helpful to everyone!

In-depth discussion of how vite parses .env files In-depth discussion of how vite parses .env files Jan 24, 2023 am 05:30 AM

When using the Vue framework to develop front-end projects, we will deploy multiple environments when deploying. Often the interface domain names called by development, testing and online environments are different. How can we make the distinction? That is using environment variables and patterns.

See all articles