Vue stepping pit series

Vue stepping pit series

1. The data on the routing change page is not refreshed

  • This happens because the route-dependent params parameter acquisition is written in the created lifecycle. Because of the lazy loading of the route, exiting the page and entering another article page will not run the created component lifecycle, resulting in article data for the first time incoming data
  • Solution: watch monitors whether the route changes
watch: {
 // 方法1
  '$route' (to, from) { //监听路由是否变化
    if(this.$route.params.articleId){// 判断条件1  判断传递值的变化
      //获取文章数据
    }
  }
  //方法2
  '$route'(to, from) {
    if (to.path == "/page") {    /// 判断条件2  监听路由名 监听你从什么路由跳转过来的
       this.message = this.$route.query.msg    
    }
  }
}

2. Using this in the asynchronous callback function cannot point to the Vue instance object

//setTimeout/setInterval ajax Promise等等
data(){
  return{
    ...
  }
},
methods (){
     setTimeout(function () {   //其它几种情况相同
      console.log(this);//此时this指向并不是vue实例 导致操作的一些ma'f
    },1000);
}

  • Solution variable assignment and arrow functions
//使用变量访问this实例
let self=this;   
    setTimeout(function () {  
      console.log(self);//使用self变量访问this实例
    },1000);

 //箭头函数访问this实例 因为箭头函数本身没有绑定this
 setTimeout(() => { 
   console.log(this);
 }, 500);

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

  • For example, some bullet screens and revolving lantern texts, which need to be called regularly, after the route jumps, because the component has been destroyed, but the setInterval has not been destroyed, and the background call continues, the console will continue to report errors. If the calculation is large, If it cannot be cleared in time, it will cause serious page freeze.
  • Solution: Stop setInterval in the component life cycle beforeDestroy
//组件销毁前执行的钩子函数,跟其他生命周期钩子函数的用法相同。
beforeDestroy(){
     //我通常是把setInterval()定时器赋值给this实例,然后就可以像下面这么停止。
    clearInterval(this.intervalId);
},

4. Vue axios sends a post request and cannot receive parameters in the background

使用vue-axios发送post请求默认是Request Payload格式,而使用ajax请求传值是Form Data格式,故需要将Request Payload 转为Form Data格式
  1. use qs
  • Install the qs module: npm install qs --save-dev
  • Introduce in the page that needs to be used: import qs from 'qs'
  • Use qs:
let postData = qs.stringify({
       account: this.account,
       pwd: this.pwd
})
  1. Use the FormData class
import axios from 'axios'
let data = new FormData();
data.append('code','1234');
data.append('name','yyyy');
this.axios.post(`${this.$url}/test/testRequest`,data)
.then(res=>{
    console.log('res=>',res);            
})

Guess you like

Origin blog.csdn.net/d2235405415/article/details/96155655