Home  >  Article  >  Web Front-end  >  Summary of several issues in Vue practice

Summary of several issues in Vue practice

小云云
小云云Original
2018-01-29 13:14:471704browse

We will always encounter some problems during the practice of Vue. In this article, we will list these problems and share solutions with you, hoping to help everyone.

This article records the problems encountered by individuals as follows:

  1. The routing change page data does not refresh problem

  2. setTimeout/setInterval this points to change and cannot access the VUe instance with this

  3. setInterval routing jump continues to run and is not destroyed

  4. vue scrolling behavior ( Browser fallback memory position) Usage

  5. vue routing intercepts browser fallback to implement similar requirements for draft saving

  6. v-once only renders elements and Component once, optimize and update rendering performance

  7. vue framework style guide recommendation

Route change page data does not refresh problem

Scenario : For example, article details data is obtained by relying on the params parameter of the route (ajax is written in the created life cycle). Because of the lazy loading of the route, exiting the page and entering another article page will not run the created component. Life cycle, the article data is still the data of the previous article.

Solution: watch to monitor whether the routing changes

 watch: {
  '$route' (to, from) { //监听路由是否变化
    if(this.$route.params.articleId){//是否有文章id
      //获取文章数据
    }
  }
}

setTimeout/setInterval this points to change and cannot use this to access the VUe instance

Scenario:

  mounted(){ 
        setTimeout(function () { //setInterval同理 
          console.log(this);//此时this指向Window对象
        },1000);
    }

Solution Method: Use arrow function or

    //箭头函数访问this实例 因为箭头函数本身没有绑定this
     setTimeout(() => { 
       console.log(this);
    }, 500);
    //使用变量访问this实例
    let self=this;
        setTimeout(function () {  
          console.log(self);//使用self变量访问this实例
        },1000);

setInterval route jump to continue running without destroying

Scenario:

For example, some barrages, revolving text, etc. need to be called regularly. , after the route jump, because the component has been destroyed, but setInterval has not been destroyed, and the background call is still continuing, the console will continue to report errors. If the calculation amount is large, it cannot be cleared in time, which will cause serious page freezes.

Solution: Stop setInterval in the component life cycle beforeDestroy

The hook function executed before the component is destroyed is the same as other life cycle hook functions.

beforeDestroy(){
     //我通常是把setInterval()定时器赋值给this实例,然后就可以像下面这么暂停。
    clearInterval(this.intervalid);
},

vue scrolling behavior (browser rollback memory position) usage

I thought it was very difficult when I did this, but later I found out that it was just a setting (provided that it is turned on History mode of routing), let’s make a simple sharing below.

Routing settings

  1. To use this function, you first need to enable the history mode of vue-router

If you have been doing it before The hash mode (default mode) is used. The project has been developed for a period of time, and then you may encounter the following problems when switching to history mode:

  1. Scrolling behavior specific The settings are as follows:

    const router = new VueRouter({
    mode: 'history',
    scrollBehavior (to, from, savedPosition) {
    //savedPosition

    if (savedPosition) { //如果savedPosition存在,滚动条会自动跳到记录的值的地方
      return savedPosition
    } else {
      return { x: 0, y: 0 }//savedPosition也是一个记录x轴和y轴位置的对象
     }
    },

    routes: [...]
    })

vue scrolling behavior document, you can go here to see more detailed information.

vue routing intercepts the browser retreat to implement similar requirements for draft saving

Scenario:

In order to prevent the user from leaving suddenly, the entered information is not saved.

Usage:

//在路由组件中:
mounted(){
},
beforeRouteLeave (to, from, next) {
  if(用户已经输入信息){
    //出现弹窗提醒保存草稿,或者自动后台为其保存
    
  }else{
    next(true);//用户离开
  }

Similar ones include beforeEach and beforeRouteUpdate, which are also divided into global hooks and component hooks. See routing documentation.

v-once only renders elements and components once, optimizing and updating rendering performance

I think the API of v-once is quite 6, and many friends may not have noticed this API.

Document introduction:

Summary of several issues in Vue practice

In my opinion, this API is mainly used for one-time rendering and there will be no further operations. Change these rendered values ​​so that you can optimize update performance for two-way bindings.

Documentation recommendation: Use v-once for low-overhead static components

Although rendering HTML in Vue is fast, you can consider using v-once when the component contains a lot of static content Cache the rendering results, like this:

Vue.component('terms-of-service', {
  template: '\
    <p v-once>\
      <h1>Terms of Service</h1>\
      ...很多静态内容...\
    </p>\
  '
})

Vue style guide recommendation:

Writing this, I thought that the vue framework also has a recommended style guide, as shown in the figure below, you can also learn from it One wave.

Summary of several issues in Vue practice

Related recommendations:

Vue.js2.0 change summary sharing

Vue.js 2.5 new feature sharing

Detailed explanation of Vue.js components and templates



The above is the detailed content of Summary of several issues in Vue practice. 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