vue9-axios、细节和杂项

十六、axios

介绍

  1. 为什么选则它
    • vue作者不再维护vue-resource,推荐使用vxios
    • 可以在node环境中使用
    • 可以拦截请求
    • 可以拦截响应数据处理
  2. 支持的请求方式,满足resful,和jq的有点像
    1. axios(config) :默认是get,参数是一个对象
    2. axios.request(config)
    3. axios.get(url [, config])
    4. axios.delete(url [, config])
    5. axios.head(url [, config])
    6. axios.post(url [, data [, config] ])
    7. axios.put(url [, data [, config] ])
    8. axios.patch(url [, data [, config] ])
  3. 内部封装了promise
  4. 会根据提供的参数数据自动转换:content-type
  5. 会在跨域并使用content-type:application、json变成非简单请求的时候,预请求一个options方法到后台,不处理的话造成后台传参错误

使用

初步使用
import axios from 'axios'

axios.defaults.baseURL = 'https://httpbin.org'
axios.defaults.timeout = 5000
axios({
  // url:'http://123.207.32.32:8080/home/mutidata',
  url: 'post',
  method: 'post',
  // 拼接在URL后
  params: {
    name: 1
  },
  // 请求体中的参数
  data: {
    type: 'sell',
    page: 3
  },
  //拦截请求
  transformRequest:[function (query) {

  }],
  //拦截返回数据
  transformResponse:[function (response) {

  }],
}).then(res => {
  console.log(res);
})

// 同时处理多个异步请求,最后返回一个数据数组,像java的栅栏
axios.all([axios({url: 'post', method: 'post'}), axios({url: 'get'})]).then(res => {
  console.log(res);
})

//处理返回的结果数组,使用的是数组的解构是根据下标解构的
axios.all([axios({url: 'post', method: 'post'}), axios({url: 'get'})])
  .then(([res1, res2]) => {
    console.log(res1);
    console.log(res2);
  })
// 这样也可以
axios.all([axios({url: 'post', method: 'post'}), axios({url: 'get'})])
  .then(
    axios.spread((res1, res2) => {
      console.log(res1);
      console.log(res2);
    }))

进一步封装

避免使用全局的axios,可能每个模块的请求是不一样的

  1. 使用的时候导入就可以了
  2. transformrequest和axiosInstance.interceptors.request.use 不冲突后者先调用
  3. transformResponse和axiosInstance.interceptors.response前者先调用

新建/network/request.js

import axios from "axios";

export function request(config) {
  if (!config.baseURL) {
    config.baseURL = 'https://httpbin.org'
  }
  if (!config.timeout) {
    config.timeout = 5000;
  }
  const axiosInstance = axios.create(config);
  //req是请求参数对象
  axiosInstance.interceptors.request.use(req => {
    console.log(req);
    //1.可以修改一些请求的参数
    // 2.可以设置一个加载图片
    return req
  })
  //res是返回的对象
  axiosInstance.interceptors.response.use(res => {
    console.log(res.data);
    return res.data
  })
  return axiosInstance(config);
}

十七、细节和杂项

this.$refs.[refName]

只会取当前模块的引用

style标签里的scoped

只会作用当前的组件的css

组件是不能直接监听原生事件的,需要:@click.native=""

main.js里设置Vue.config.productionTip = false和true的区别

  • 是一个全局配置属性2.2.0 新增
  • 设置为 false 以阻止 vue 在启动时生成生产提示。

vue文件可以首字母大写,如果首字母大写你使用组件的时候可以用-为分隔符,TabBar标签使用的时候可使用tab-bar

使用':style'

:style 后面是对象的时候里面的属性值是字符串格式

vue表单提交:其他方式

controller

@RequestMapping("save")
public ResponseModel savenew(@RequestBody @Validated SysUser user, BindingResult 		result) {
        if (result.hasErrors()) {
            return ResponseModel.FAIL()
                    .setMsg(result.getAllErrors()
                            .stream()
                            .map(err->err.getDefaultMessage())
                                    .collect(Collectors.joining(";"))
                            );
        }
        String password = user.getPassword();
        if (password.length() < 32) {
            user.setPassword(CryptUtil.shiroEncry(user));
        }
        userService.save(user);
        return ResponseModel.SUCCESS();
}

vue

<template>
	<div id="user">
		<div>
			姓名:
			<input type="text" name="username" v-model="entity.username"/>
		</div>
		<div>
			密码:
			<input type="password" v-model="entity.password" />
		</div>
		<div>
			电话:
			<input type="text" v-model="entity.phone" />
		</div>
		<div>
			电话:
			<input type="text" v-model="entity.role.roleName" />
		</div>
		<button @click="saveUserInfo">保存</button>
	</div>
</template>

<script>
	import {
		saveUser
	} from 'network/module/user.js';

	export default {
		name: "User",
		methods: {
			saveUserInfo() {
				saveUser(this.entity).then(res=>alert(res.msg));
			}
		},
		data(){
			return {
				entity:{
					role:{}
				}
			}
		}
	};
</script>

415Unsupported Media Type错误

前端工具请求接口的类型和后端服务器定义的类型不一致造成

vue跨域

vue.config.js

//vue-cli3配置这个做代理
	devServer: {
		proxy: {
			'/api': {
				target: 'http://localhost:8080/mall/api', //API服务器的地址
				changeOrigin: true, // 是否跨域
				pathRewrite: {
					'^/api': ''
				}
			}
		},
	},
	//vue-cli2使用这个
	// dev: {
	// 	proxyTable: {
	// 		'/api': {
	// 			target: 'http://localhost:8080/mall/api', //API服务器的地址
	// 			changeOrigin: true, // 是否跨域
	// 			pathRewrite: {
	// 				'^/api': ''
	// 			}
	// 		}
	// 	}
	// },

qs的嵌套对象序列化问题

qs官网

  • 手写嵌套对象:

    {
        a:{
            'b.c':d
        }
    }
    
  • qs默认嵌套对象的序列化会用 ‘[]’

    //{ allowDots: true }会将【】转换成 ‘.’
    this.$qs.stringify(obj,{ allowDots: true })
    

简单请求和非简单请求

阮一峰跨域

package.js中的^和~区别

npm官网

~1.15.2 := >=1.15.2 <1.16.0 匹配到第二位,大于当前版本小于1.16.0

^3.3.4 := >=3.3.4 <4.0.0 匹配到第一位所有大于当前版本且小于4

vue常用插件

详情

Vue.nextTick

this.$nextTick(function)将回调延迟到下次 DOM 更新循环之后执行,vm.$nextTick() 实例方法特别方便,因为它不需要全局 Vue,并且回调函数中的 this 将自动绑定到当前的 Vue 实例上

@load的时候总是不生效

  • image src有值的时候,才开始加载
  • onload事件是在src的资源加载完毕的时候,才会触发
posted @ 2020-03-02 11:31  zpyu521  阅读(194)  评论(0编辑  收藏  举报