人类高质量vue学习笔记(二)

1,314 阅读6分钟

1. 生命周期

所谓生命周期,指的就是生命从出生到死亡的一个过程。Vue 的生命周期指的是 Vue 实例从创建到销毁的一个过程。这个过程常常会伴着一些函数的自调用,我们把这些函数称为钩子函数

生命周期图示:官方图


vue 生命周期中常用的钩子函数:

方法名讲解
beforeCreateel没有绑定作用域,没有 data、methods等属性,说白了就是穷光蛋一个,啥也干不了
created已经初始化了data属性和methods中相关方法,但是页面还没有渲染出来
beforeMountel 绑定了作用域,但是页面上还没有真实数据
mounted数据已经渲染到页面中
beforeUpdatedata数据更新时调用,此时页面上还是旧数据
updateddata数据更新时调用,此时页面上已经是更新过后的数据
beforeDestroy销毁之前调用,此时data、methods等还没有被销毁
destroyed销毁调用!全部干掉!

vue 的生命周期大家了解即可,只需记住一点:页面渲染之前获取数据的方法 在created()里面调用。例如后台管理员登录成功进入用户管理界面,需要显示用户的信息,我们就可以这样写:

 created() {
    this.init();
  },
 methods: {
    // 初始化方法
    init() {
      // 发起异步请求获取用户信息
    },

2. 计算属性

我们知道可以通过插值表达式显示 data 属性中的值,例如{{username}}。

但是有时候我们需要将 data 中的多个属性结合起来进行显示,比如显示某个班所有同学的数学总成绩,这个时候我们就可以使用计算属性。

计算属性可以将数据进行缓存,所以会大大提高访问效率。

计算属性写在 vue 实例中的 computed中:

<script>
 const app = new Vue({
    el: '#app',
    data: {
        msg:"我爱你中国"
    },
    methods: {

    },
    computed:{

    }
 });
</script>

2.1 案例一:显示完整姓名

<div id ="app"> 
    特斯拉CEO: {{fullName}}
</div>
<script src="https://cdn.jsdelivr.net/npm/vue/dist/vue.js"></script>
<script>
 const app = new Vue({
    el: '#app',
    data: {
        firstName: "埃隆" ,
        lastName: "马斯克 "
    },
    methods: {

    },
    computed:{
        fullName(){
            return this.firstName+"."+this.lastName;
        }
    }
 });
</script>

运行结果:

2.2 案例二:显示总成绩

<div id ="app"> 
  <span v-for="(student, index) in students" :key="student.id">
        {{index}} {{student.name}} {{student.score}} <br>
   </span>
   总成绩:{{totalScore}}
</div>
<script src="https://cdn.jsdelivr.net/npm/vue/dist/vue.js"></script>
<script>
 const app = new Vue({
    el: '#app',
    data: {
        students:[
            {id:1,name:"小明",score:100},
            {id:2,name:"小红",score:200},
            {id:3,name:"小周",score:300}
        ]
    },
    methods: {

    },
    computed:{
        totalScore(){
            return this.students.reduce((sum,student)=>{ return sum + student.score },0);
        }
    }
 });
</script>

运行结果:

3. 监听器

  • 关键词:watch
  • 用来监听数据的变化
  • 监听的属性必须是 data 已经存在的

案例

<div id ="app"> 
    <input type="text" v-model="name" > 
</div>
<script src="https://cdn.jsdelivr.net/npm/vue/dist/vue.js"></script>
<script>
 const app = new Vue({
    el: '#app',
    data: {
       name: "张无忌"
    },
    methods: {

    },
    computed:{

    },
    watch:{
        name(newValue){
            console.log("改变后的名字:"+newValue);
        }
    }
 });
</script>            

运行结果:

4. 过滤器

  • 关键词:filters
  • 用于常见的文本的格式化
  • 不改变 data 属性的值,而是改变渲染之后的结果
  • 可以用在两个地方:{{}} 和 v-bind 表达式
  • 过滤器一定要有返回值

案例:格式化时间

<div id="app"> 
  <span>格式化之前:{{ time}}</span><br>
  <span>格式化之后:{{ time | timeFormat}}</span>
</div>
<script src="https://cdn.jsdelivr.net/npm/vue/dist/vue.js"></script>
<script>
  const app = new Vue({
      el: '#app',
      data: {
          time: "2021年8月22日"
      },
      methods: {
      },
      filters: {
          timeFormat(time){
              if(time.indexOf("年") != -1){
                  time = time.replace(/年/,"-");
              }
              if(time.indexOf("月") != -1){
                  time = time.replace(/月/,"-");
              }
              if(time.indexOf("日") != -1){
                  time = time.replace(/日/,"");
              }
              return time;
          }
      }
  });
</script>

运行结果:

5. axios

  • axios 是一个异步请求技术,用来在页面中发起异步请求
  • 能够自动转换 JSON 数据
  • 通过 CDN 引入:
<script src="https://unpkg.com/axios/dist/axios.min.js"></script>

5.1 Get 请求

5.11 不带参数

axios.get('http://localhost/api/user').then(function(res){ 
  #注意:所有的数据都存在 res 的 data 属性里面
  console.log(res.data)
})

5.12 以 ?的形式传参

axios.get('http://localhost/api/user?id=10').then(function(res){ 
   #注意:所有的数据都存在 res 的 data 属性里面
  console.log(res.data)
})

5.13 restul 形式传参

axios.get('http://localhost/api/user/1234').then(function(res){ 
  #注意:所有的数据都存在 res 的 data 属性里面
  console.log(res.data)
})

5.14 params 形式传参

axios.get('http://localhost/api/user',{
      params: {
        id: 123
      }).then(function(res){ 
  #注意:所有的数据都存在 res 的 data 属性里面
  console.log(res.data)
})

5.2 Post 请求

axios.post('http://localhost/api/user', {
      id: 123,
      typeId: 1234
}).then(function(res){
 #注意:所有的数据都存在 res 的 data 属性里面
  console.log(res.data)
})

5.3 全局配置

5.3.1 配置公共的请求头

axios.defaults.baseURL = 'https://localhost/api';

配置完公共的请求头之后,axios 的请求路径就可以简写了:

axios.get('/user').then(function(res){ 
  #注意:所有的数据都存在 res 的 data 属性里面
  console.log(res.data)
})

5.3.2 配置 超时时间

axios.defaults.timeout = 1000;

5.4 拦截器

  • 请求拦截器:在用户发起请求前进行一些操作,例如在所有的请求头都添加上 token
  • 响应拦截器:接收响应后进行一些操作
# 1. 请求拦截器:全局设置 token
axios.interceptors.request.use(function (config) {
  let token = sessionStorage.getItem('token')
  if (token) {
    config.headers['token'] = token
  }
  return config
})
#2. 响应拦截器 
axios.interceptors.response.use(function(res) {
  var data = res.data;
  return data;
}, function(err){

})

5.5 async 和 await

有时候我们一个业务需要一次调用多个接口,并且后一个接口需要依赖前一个接口调用的结果,如果前一个接口挂了,后面就会全军覆没,例如:

axios.get('http://localhost/api/user').then(function(res){ 
   if(res.data.success){
       axios.get('http://localhost/api/data').then(function(res){ 
        if(res.data.success){
            ......
          }   
        })
    }   
})

上面的例子就是在套娃,代码体验不是很好,所以我们引入了 async 和 await。

async 作为一个关键字放到函数前面,表示该函数是一个异步函数,也就意味着该函数的执行不会阻塞后面代码的执行。例如:

async getUser(){

}

await 是等待的意思,等待后面的代码执行完并返回一个结果。await 后面可以跟任何表达式,也是非阻塞的。

async 和 await 结合使用:

async getUser(){
  let result = await axios.get('http://localhost/api/user');
  if(result.data.success){
    let typeId = result.data.typeId;
    let type = await axios.get('http://localhost/api/getType?typeId='+typeId);
    ......
  } 
}

这样看起来是不是比较美观一点!

6. 数组常用操作

6.1 返回数组长度

   var arr= [1,12,8,30];
   var len = arr.length;
   console.log(len);//结果为4

6.2 将数组合并成字符串

  var arr= [1,12,8,30];
  var str = arr.join(",");
  console.log(str)

打印结果:

6.3 添加元素:push 和 unshift

  • push 是在数组尾部添加元素
  • unshift 是在数组头部添加元素
 var arr = [1,12,8,30];
 arr.push(99);
 arr.unshift(100);
 console.log(arr);

打印结果:

6.4 替换元素:splice

  • 第一个参数,要替换的元素的下标。注:数组下标从0开始
  • 第二个参数:替换的元素的个数,从第一个下标开始
  • 第三个参数:要替换成什么
 var arr = [1,12,8,30];
 arr.splice(2,1,"66");
 console.log(arr);

打印结果:

6.5 删除元素:pop 和 splice

  • pop 是删除数组最后一个元素
  • splice 是根据元素下标删除元素,第一个参数:要删除的元素的初始坐标,第二个参数:要删除的元素个数
var arr = [1,12,8,30];
arr.pop();// 删除 30
arr.splice(0,1);// 删除 1
console.log(arr);

打印结果:

6.6 数组倒序

var arr = [1,12,8,30];
arr.reverse();
console.log(arr);

打印结果:

6.7 过滤条件返回新的数组:filter

 var arr = [1,12,8,30];
 const newArr = arr.filter(item => item >2);
 console.log(arr);
 console.log(newArr);

打印结果:

6.8 合并多个数组:concat

var a = [1,12,8,30];
var b = [666,777];
var c = a.concat(b);
console.log(c);

打印结果:

6.9 返回指定数组:slice

  • slice 不会改变原来数组的值
  • 第一个参数:要返回的数组的初始坐标
  • 第二个参数:返回数组元素的个数
var arr = [1,12,8,30];
var newArr = arr.slice(0,2);
console.log(arr);
console.log(newArr);

打印结果: