052: Vue re-release, some experience examples in software hot update

Insert image description here

No. 052

View here: VUE ------ element UI


Column goal

Under the control of the joint technology stack of vue and element UI, this column provides effective source code examples and information point introductions for flexible use.

(1) Provide some basic operations of vue2: installation, reference, template use, computed, watch, life cycle (beforeCreate, created, beforeMount, mounted, beforeUpdate, updated, beforeDestroy, destroyed, activated, deactivated, errorCaptured, components,), $root , $parent , $children , $slots , $refs , props, $emit , eventbus ,provide / inject, Vue.observable, $listeners, $attrs, $nextTick , v-for, v-if, v-else ,v-else-if, v-on, v-pre, v-cloak, v-once, v-model, v-html, v-text, keep-alive, slot-scope, filters, v-bind,. stop, .native, directives, mixin, render, internationalization, Vue Router, etc.

(2) 提供element UI的经典操作: -cascader, el-input-number, el-switch, el-slider, el-time-picker, el-date-picker, el-upload, el-rate, el-color-picker, el-transfer, el-form , el-table, el-tree, el-pagination, el-badge, el-avatar, el-skeleton, el-empty, el-descriptions, el-result, el-statistic, el-alert, v-loading, $ message, $alert, $prompt, $confirm , $notify, el-breadcrumb, el-page-header, el-tabs, el-dropdown, el-steps, el-dialog, el-tooltip, el-popover, el- popconfirm, el-card, el-carousel, el-collapse, el-timeline, el-divider, el-calendar, el-image, el-backtop,v-infinite-scroll, el-drawer等

Application scenarios

When working on a vue project, every time a new version is packaged and released to the server, the corresponding js, css and other file fingerprints will change. How to do hot update? In the author's project, a lot of user-related information is stored in localstorage. When new releases are made, some information must be changed. At this time, the user is required to log in again and re-obtain the information and store it in local storage.

1. Configure the release version and force log out and log in again if it is not unified.

Insert image description here
During the software development process, in order to facilitate the management and control of software versions, corresponding version number rules are generally formulated based on the software development progress and release plan. Common version number formats include the following:

  • Major Version Number: Indicates major updates and improvements to the software. Generally, the software will be upgraded when there are major changes in functionality or incompatibility. Generally, numbers are used. express.
  • Minor Version Number: Indicates minor updates and improvements to the software. Generally, the software will be upgraded when there are certain improvements or new functions in the software. Generally, numbers are used. express.
  • Patch Version Number: Indicates software repairs and bug corrections. Generally, an updated version will be released when a vulnerability or error occurs in the software, and is generally represented by a number.
  • Build Version Number: Indicates the compiled version and build number of the software. It is generally used to distinguish different build versions and is generally represented by numbers or letters.

(1) Configure the version number in main.js

Insert image description here

(2) Determine on the main page whether the newly released version is consistent with the version number in localstorage

			getVersion(){
    
    
				let v = localStorage.getItem("version");
				if (v!= null) {
    
    
					if(v!=this.$root.version){
    
    
						this.$router.push({
    
    path: "/login"})
					}
				} else {
    
    
                  this.$router.push({
    
    path: "/login"})
				}				
			},

Call it in the mounted life cycle

mounted() {

this.getVersion();
}

(3) Determine to add and delete the version item of localStorage on the login page

mounted(){
localStorage.removeItem(“version”);
}

Add this sentence to the login success function

localStorage.setItem(“version”, this.$root.version)

If the version is inconsistent at this point, you will log in again to obtain the new version number information.

2. The client keeps hanging up and the page does not close. You need to make a judgment regularly and force to log in again.

The blogger adopted the solution for this articlehttps://blog.csdn.net/weixin_42000816/article/details/131800399.

The idea of ​​the new solution is to poll and request the index.html file and parse the js files inside. Since each js file has a fingerprint identification after Vue packaging, you can compare the fingerprints after each packaging and analyze whether there are changes in the file. If there are changes, the user will be prompted to update
Insert image description here

auto-update.js

let lastSrcs; //上一次获取到的script地址
let needTip = true; // 默认开启提示

const scriptReg = /<script.*src=["'](?<src>[^"']+)/gm;

async function extractNewScripts() {
    
    
	const html = await fetch('/?_timestamp=' + Date.now()).then((resp) => resp.text());
	scriptReg.lastIndex = 0;
	let result = [];
	let match;
	while ((match = scriptReg.exec(html))) {
    
    
		result.push(match.groups.src)
	}
	return result;
}

async function needUpdate() {
    
    
	const newScripts = await extractNewScripts();
	if (!lastSrcs) {
    
    
		lastSrcs = newScripts;
		return false;
	}
	let result = false;
	if (lastSrcs.length !== newScripts.length) {
    
    
		result = true;
	}
	for (let i = 0; i < lastSrcs.length; i++) {
    
    
		if (lastSrcs[i] !== newScripts[i]) {
    
    
			result = true;
			break
		}
	}
	lastSrcs = newScripts;
	return result;
}
const DURATION = 5000;

function autoRefresh() {
    
    
	setTimeout(async () => {
    
    
		const willUpdate = await needUpdate();
		if (willUpdate) {
    
    
			const result = confirm("页面有更新,请刷新查看");
			if (result) {
    
    
			  location.href('/login');
			}
                 needTip = false; 
		}
                if(needTip){
    
    
			autoRefresh();
		}
	}, DURATION)
}
autoRefresh();

Note: It is slightly different from the original author's judgment, that is, the page is not refreshed automatically, but jumps to the login page.

Introduced in main.js

import “@/utils/auto-update.js”

Backend processing solution

Later, my back-end colleagues came up with a simpler and more practical solution, which was to set up negotiation cache and strong cache on nginx, eliminating the need for the front-end to handle it.

location /test {
    
    
    #try_files $uri $uri/ /notFound.html;
    #index index.html index.htm;

    if ($request_uri ~* .*[.](js|css|map|jpg|png|svg|ico)$) {
    
    
      add_header Cache-Control "public, max-age=25920000";#非html缓存1个月
    }

    if ($request_filename ~* ^.*[.](html|htm)$) {
    
    
      add_header Cache-Control "public, no-cache";
    }
  }

Reference information : https://article.juejin.cn/post/7215881683294879801

Guess you like

Origin blog.csdn.net/cuclife/article/details/134970881