Recently when I was working on a project, I found that I was really not familiar with vue-Router. I only knew a simple usage and started to work on it. I couldn’t figure out the original simple problem. Now go back over the document and comb it out again.

Principle of VUE routing

To tell the truth, ROUTE I have been also patronized to use, did not seriously think about this problem, or that somebody else interview asked this, I just reaction is should have a good understanding.

The jump page without refreshing is one of the advantages of single-page applications. It provides good user experience and fast loading speed. The jump page of VUE routes is refresh-free and has two forms. Hash mode, whereby a hashchange event is triggered to render the page dynamically by adding the # + route name after the link, based on changes in the matching field. It is similar to the a link being used as an anchor on the page, which does not refresh the page.

Another option is history mode, which is the browser’s history API, pushState and replaceState. This can also be done by calling pushState on the browser’s history object, changing the current address, and listening for the browser’s back and forward events in combination with window.onpopState. Unlike pushStete, replaceState replaces a record and pushStete adds a record.

See the MDN documentation for the use of pushState. This API and Ajax together constitute the PJAX technology, is also used to achieve a page refresh free loading method, often used in THE PC long list page flipping, the most important advantage over the hash mode is that there is no annoying # symbol, For example, on the same list page, in hash mode, the URL appears as http://yoursite.com/#/list, which is uncomfortable to look at. In the history mode, the URL link is shown as http://yoursite.com/list, which looks quite refreshing ~ and ~ BELIEVE that did wechat public account development all understand, this damn # how annoying ~ in the following application scenarios, I will talk about this problem ~

So the question is, since history mode looks good and functions just as well, why are more people still using hash mode? Because of the history mode, you also need to configure it on the server, otherwise refreshing the page will generate a 404 error. This is easier to understand because we are actually using pushState to jump to the page, rather than actually requesting another list. HTML file from the server, which is not found at http://yoursite.com/#/list

For nginx servers, add try_files $uri $uri/ /index.html to location /; Can. This line of code says: If you do not match the path of the static resource, you will redirect to the index page, so that there is no error. Using history mode is a bit more difficult, but it’s not a big deal

There are two modes of parameter transmission in the VUE route

There are only two types of page arguments, query and params. Params is displayed in the URL as /params, and query is displayed as? Query =query1 is displayed in the URL. In addition, the params parameter needs to be configured to the route definition, otherwise it will not be displayed in the URL and the refresh will disappear.

If you pass the params parameter, do not use the path field, otherwise it will not work. The query parameter does not have this limitation, using either the name or path fields. This is easy! But you have to do it yourself to remember. Anyway I was early to see, but always remember mixed ~ ~ re use demo to write again just remember ~ and what others say is not necessarily right, or to experiment again to know it. ╮ (╯ del ╰) ╭

Jump of the VUE route

The hop of a VUE route is divided into two types. The first type is declarative. The

is used to declare the hop, and the to attribute defines the hop parameters. The other is programmatic, using router.go(), router.push(), router.replace() to jump. The Go method is the same as the browser’s history API, and can go back to the previous page.

The difference between the push method and the replace method is that the push method adds the current page to the history, which can be returned by history.go(-1). The replace method replaces the current record in the history. If you go back to the previous page, it doesn’t go back to the previous page. If there was no previous page, it doesn’t go back.

Vue route guard

The VUE route guard is divided into three types. One is the global route guard, which is usually set after the route is instantiated to do some general routing operations. All its routes will perform operations. One is a guard that is exclusive to a single route. It is set when a single route is defined and all jumps are executed by the route. The other is intra-component guards, which only work within components.

Global routing guard type:

  • router.beforeEach(to, from, next)
  • router.afterEach(to, from, next)

Route exclusive guard:

  • beforeEnter(to, from, next)

Component exclusive guard:

  • beforeRouteEnter(to, from, next)
  • beforeRouteUpdate(to, from, next)Called when the component instance is being reused when the dynamic parameter path changes.
  • beforeRouteLeave(to, from, next)Called when the navigation leaves the component’s route.

Some application scenarios of VUE routing

When to use push and when to use replace

At the beginning, I mostly used push() or go() for route jump, and seldom used replace(). Later, I found this missing API when I looked through the documents under business requirements. In simple terms, when you need to go from page A to page B, to page C, and back again, you can go straight back to page A. Use replace() to jump from page B to page C.

Dynamically change the title of the page

  • When defining the route, add a title attribute to the meta field of the route and define the page title name.
  • Route guard at global levelbeforeEach()Method to add a judgment, get the meta field of the route, and dynamically change the page title.
// router.js
{
	path: '/index',
	name: 'index',
	meta: {
		title: 'home'
	}
}

// main.js
router.beforeEach(to, from, next){
	if(to.meta. Title){document.title = to.meta. Title} next()Copy the code

Failure of parameter transfer or redirect caused by single page application URL in wechat development

Wechat authorized jump

When making wechat authorized redirect, if there is # sign inside the link in hash mode, the redirect may fail. Use encodeURIComponent to process the page address and then pass it in.

let _url = encodeURIComponent(location.href)
location.href = `https://open.weixin.qq.com/connect/oauth2/authorize?appid=${this.appid}&redirect_uri=${_url}&response_type=code&scope=snsapi_base&state=#wechat_redirect`
Copy the code

Get the WxConfig configuration

It is relatively simple for the front end to obtain wxConfig. The main operations are in the back end. The front end only needs to pass a URL parameter, and the back end obtains the config parameter and sends it back to the front end. When the front end gets the parameters, it calls the wx.config method.

let url = location.href.split(The '#')[0]
http.get('weixin/config',{
    params:{
        url: encodeURIComponent(url)
    }
})
.then(res=>{
    wx.config({
        beta: true// The wx.invoke jsAPI will have a problem:false// If debug mode is enabled, the return value of all API calls will be displayed in the client side alert. To view the passed parameters, you can open it in the PC side and the parameter information will pass throughlogPrint, print only on PC. AppId: res.data.appId, // Required, enterprise wechat corpID timestamp: res.data.timestamp, // Required, generated signature timestamp nonceStr: Res.data. nonceStr, // Required, generate a random string of signatures signature: res.data.signature,// Required, signature, see appendix -js-SDK Use permission signature algorithm jsApiList: ['scanQRCode'}) // Check wechat wx.error()function(res){// If the config information fails to be verified, the error function will be executed. For example, the verification fails due to the expiration of the signature. You can view the specific error information in the debug mode of config or in the returned res parameter. console.log('Error message ====',res)
    })
})
Copy the code

Single page application plus Baidu statistics

In the single page application above, if the baidu statistics directly to HTML code without any processing, is less than the statistics of the page view, so add JS and monitor jump page code are written to main.js inside.

// Add baidu statistics first determine whether the production environment or development environment if the development environment do not addif(process.env.NODE_ENV ! = ='development') {
    let_hmt = _hmt || []; window._hmt = _hmt; // You must mount _hmt to the window, otherwise you cannot find it (function() {
        var hm = document.createElement("script");
        hm.src = "https://hm.baidu.com/hm.js?yourappid";
        var s = document.getElementsByTagName("script") [0]; s.parentNode.insertBefore(hm, s); })()} route. beforeEach(to, from, next){// Add baidu statistics code first determine whether it is production environment or development environmentif(process.env.NODE_ENV ! = ='development') {// Add page statisticsif (_hmt) {
            if (to.path) {
                _hmt.push(['_trackPageview'.'/ #'+ to.fullPath]); }}}}Copy the code

Reference: segmentfault.com/a/119000001… www.jianshu.com/p/febd38110…