axios封装、token、vue2中$set的使用


一、axios封装

引入axios import axios from ‘axios’
使用自定义的配置文件发送请求
添加请求拦截器
添加相应拦截器
导出
封装axios好处:达到扩展和易用的目的,降低耦合度

// 对http请求进行封装
import axios from 'axios'

// 使用自定义的配置文件发送请求
const instance = axios.create({
    
    
    baseURL: '',
    timeout: 5000,
    headers: {
    
    
    }
});
// 添加请求拦截器
instance.interceptors.request.use(function (config) {
    
    
    // 在发送请求之前做些什么
    return config;
  }, function (error) {
    
    
    // 对请求错误做些什么
    return Promise.reject(error);
  });

// 添加响应拦截器
instance.interceptors.response.use(function (response) {
    
    
    instance// 对响应数据做点什么
    if(response.status === 200){
    
    
        return response.data;
    }else{
    
    
        console.error("请求错误")
        console.error(response)
    }
    return response;
  }, function (error) {
    
    
    // 对响应错误做点什么
    return Promise.reject(error);
  });

  export default instance

二、token的使用

  1. 认证成功后,会对当前用户数据进行加密,生成一个加密字符串token,返还给客户端(服务器端并不进行保存)
  2. 可以将获取到的token存储到localstorage中
  3. 再次访问时服务器端对token值的处理:服务器对浏览器传来的token值进行解密,解密完成后进行用户数据的查询,如果查询成功,则通过认证,实现状态保持,所以,即时有了多台服务器,服务器也只是做了token的解密和用户数据的查询,它不需要在服务端去保留用户的认证信息或者会话信息,这就意味着基于token认证机制的应用不需要去考虑用户在哪一台服务器登录了,这就为应用的扩展提供了便利,解决了session扩展性的弊端。

三、vue2中$set的使用

1、什么场景下使用$set

set为解决Vue2中双向数据绑定失效而生,只需要关注什么时候双向数据绑定会失效就可以了。
例如:

  1. 利用数组中某个项的索引直接修改该项的时候
  2. 直接修改数组的长度时
  3. 由于JavaScript的限制,Vue2不能检测对象属性的添加或删除
arr[indexOfItem] = newValue //1、利用索引修改
arr.length = newLength//2、修改数组的长度

深入了解可参考官网:
深入响应式原理 -vue.js

2、Vue.set 和 this.$set的关系

this.$set 实例方法,该方法是全局方法 Vue.set 的一个别名

3、$set 用法

1.对于数组

this.$set(Array, index, newValue)

2.对于对象

this.$set(Object, key, value)

4、实例场景

需求:data中未定义,手动给form添加age属性,并且点击按钮进行自增。

	如果使用 this.form.age = 10 这种方式,不能进行添加和自增,数据无法响应式。
	此时便需要使用 this.$set方式实现响应式
<template>
	<div>
		<h1> {
    
    {
    
     form }} </h1>   <!--{
    
    name:'xxx'}/ {
    
    name:'xxx',age:10}-->
		<button @click="add">添加</button>
	</div>
</template>
<script>
export default{
    
    
	data(){
    
    
		return{
    
    
			form:{
    
    
				name: 'xxx',
			}
		}
	}
	methods:{
    
    
		add(){
    
    
			if(!this.form.age){
    
    
				this.$set(this.form, age, 10) // 成功
				
				// Vue2中监听不到动态给对象添加的属性的
				// this.form.age = 10   // 失败无法添加,更无法自增
			} else {
    
    
				this.form.age++
			}
		}
	}
}
</script>

猜你喜欢

转载自blog.csdn.net/qq_50906507/article/details/128188931