vue 1.x 的版本提供了一个封装库 vue-resource , 但是到了vue 2.x版本之后,这个就弃用了 vue-resource使用方法和 axios 相似度在 95% vue-resouce有jsonp方法,但是axios是没有的
vue2.x版本我们最用使用的数据请求是 axios 和 fetch
get post head put delete option …
axios得到的结果会进行一层封装,而fetch会直接得到结果
举例: axios
{data: 3, status: 200, statusText: "OK", headers: {…}, config: {…}, …} config: {adapter: ƒ, transformRequest: {…}, transformResponse: {…}, timeout: 0, xsrfCookieName: "XSRF-TOKEN", …} data: 3 headers: {content-type: "text/html; charset=UTF-8"} request: XMLHttpRequest {onreadystatechange: ƒ, readyState: 4, timeout: 0, withCredentials: false, upload: XMLHttpRequestUpload, …} status: 200 statusText: "OK" __proto__: Objectfetch
Axios总结 1.get方法
A: 无参数 axios.get(url).then(res=>console.log(res).catch(error=>conosle.log(error)) B: 有参数 axios({ url: 'http://xxx', method: 'get' //默认就是get,这个可以省略, params: { key: value } }) 2.post 注意: axios中post请求如果你直接使用npmjs.com官网文档, 会有坑 解决步骤: 1. 先设置请求头 2. 实例化 URLSearchParams的构造器函数得到params对象 3. 使用params对象身上的append方法进行数据的传参// 统一设置请求头 axios.defaults.headers.post[‘Content-Type’] = ‘application/x-www-form-urlencoded’; let params = new URLSearchParams()
// params.append(key,value)
params.append(‘a’,1) params.append(‘b’,2)
axios({ url: ‘http://localhost/post.php’, method: ‘post’, data: params, headers: { //单个请求设置请求头 ‘Content-Type’: “application/x-www-form-urlencoded” } }) .then(res => { console.log( res ) }) .catch( error => { if( error ){ throw error } })
Fetch 1.get
fetch(‘http://localhost/get.php?a=1&b=2’) .then(res=> res.text()) // 数据格式化 res.json() res.blob() .then(data => { console.log( data ) }) .catch(error => { if( error ){ throw error } })
注意事项: A: fetch 的 get 请求的参数是直接连接在url上的, 我们可以使用Node.js提供的url或是qureystring模块来将 Object --> String B: fetch 的请求返回的是Promise对象,所以我们可以使用.then().catch(),但是要记住.then()至少要写两个, 第一个then是用来格式化数据的,第二个then是可以拿到格式化后的数据 格式化处理方式有 fetch(’./data.json’) .then(res=>{ res.json() //res.text() res.blob() }) .then( data => console.log(data)) .catch( error => console.log( error ))
2.post fetch文档 https://developer.mozilla.org/zh-CN/docs/Web/API/Fetch_API/Using_Fetch#进行_fetch_请求
fetch请求博客 https://blog.csdn.net/hefeng6500/article/details/81456975
项目中:
1. computed:将需要逻辑处理的放入computed里 1. 有逻辑 2. 像变量一样使用 2. methods 事件处理程序 1. watch 异步操作( 数据请求 ) watch是一个对象,它里面存储的是 { [key: string]: string | Function | Object | Array } 往往watch我们里面常存储的是方法 watch中方法的名称就是 data 选项中数据的名称 深度监听: watch: { num: { deep: true, handler () { //数据改变之后执行的事情 } } }使用它的好处: 1. 将 options 中的配置项可以单独抽离出来,单独管理,这样方便维护 使用: 1. 新建一个对象用来保存 options 中某一个配置项,比如: methods 2. 接下来要将我们创建好的对象混入到我们的 ViewModel 中,我们的混入形式有两种 - 局部混入 【 推荐 】 只是在当前 vm 中才有 new Vue({ mixins: [ myMixin ] }) - 全局混入 在所有的vm中都会有
Vue.mixin({ methods: { aa () {} } })** Vue 2.x版本使用的就是 VDOM ( 虚拟DOM ) **
接下我们以一个案例的形式告诉大家 : 列表渲染为什么要加key?
jsx 在vue采用的原因
VDOM对象树态繁琐了, 如果能像hom结构一样书写就好了, 这就引入了 jsx
render函数是做什么的
但是jsx始终还是不能直接去用的,必须转换成 对象 才能使用, vue中 使用render 函数 解析jsx语法, 然后换成 对象结构 ,在通过 createElment 生成节点,渲染成 真实DOM