Vue2:如何通过axios发起Ajax请求

基于原生 ajax + Promise 技术封装通用于前后端的请求库。

ajax是一种前端异步请求后端的技术。
原理是:浏览器 window 接口的 XMLHttpRequest

  • 简单理解:axios 是一个专门用于发送 ajax 请求的库。

特点:

  • 支持客户端发送 Ajax 请求
  • 支持服务端 Node.js 发送请求
  • 支持 Promise 相关用法
  • 支持请求和响应的拦截器功能
  • 自动转换 JSON 数据
  • axios 底层还是原生js实现,内部通过 Promise 封装的

安装 axios

yarn add axios

语法格式

axios({
    url: '',
    mothod: 'get',
    data: {
        return {
        	key: value,		// post请求参数
    	},
    },
    params: {
        key: value,		// get请求参数
    }
}).then(res => {
    console.log(res, 'res');
}).catch(error => {
    console.log(error, 'error');
})

获取所有参数不需要写请求参数。

data:拼接到请求体的参数,post 请求的参数

params:拼接到请求行的参数,get 请求的参数

配置基础地址,统一管理

运行时,axios 的 baseURL 会自动更新。

通过 axios.defaults.baseURL 配置基础地址,相当于把公共地址提取出来,调用接口时,只需要写后面的接口地址就行。

<script>
	axios.defaults.baseURL = 'http://123.57.109.30:3006'
	
    methods: {
        axios({
            url: '/api/getbooks',
            mothod: 'get',
            data: {
                // post: value,
            }
        }).then(res => {
            console.log(res, 'res');
        }).catch(error => {
            console.log(error, 'error');
        })
    }
script>

全局配置 axios

main.js 中配置全局 axios

import axios from 'axios'
Vue.prototype.$axios = axios;
axios.defaults.baseURL = 'http://123.57.109.30:3006'

ref 和 $nextTick

ref 获取真实dom

refid 都可以获取到真实 dom

// 语法格式
this.$refs.ref名字

:ref 用于 vue组件时,可以得到组件实例,同时可以调用实例下的方法。

$nextTick 获取最新的 DOM

vue 更新数据是异步的,使用 $nextTick 同步更新。

  • data 数据改变,立刻获取 dom 内容。

$nextTick 和 updated 生命周期钩子函数都可以访问到更新后的dom。

$nextTick 函数原地返回一个Promise对象。


<script>
    this.$nextTick(funciton () {
        console.log( this.$refs.myP.innerHTML );
    });
script>

点击 count+1,实时更新

<template>
  <div>
      <p ref="myP">{{count}}p>
      <button @click="add">点击获取countbutton>
  div>
template>

<script>
export default {
    data () {
        return {
            count: 0,
        }
    },
    methods: {
        add () {
            this.count++;
            this.$nextTick(function () {
                console.log(this.$refs.myP.innerHTML);
            })
        }
    }
}
script>
应用场景

点击 button,隐藏 button,鼠标聚焦在 input 上

  • 方法一:使用 updated

    <template>
      <div>
          <input type="text" ref="myIpt" v-if="isShow">
          <button @click="isShow = true" v-else>点击搜索button>
      div>
    template>
    
    <script>
    export default {
        data () {
            return {
                isShow: false,
            }
        },
        updated () {
            this.$refs.myIpt.focus();
        }
    }
    script>
    
  • 方法二:使用 $nextTick

    <template>
      <div>
          <input type="text" ref="myIpt" v-if="isShow">
          <button @click="serach" v-else>点击搜索button>
      div>
    template>
    
    <script>
    export default {
        data () {
            return {
                isShow: false,
            }
        },
        methods: {
            serach () {
                this.isShow = true;
                
                this.$nextTick(function () {
                    this.$refs.myIpt.focus();
                })
            }
        }
    }
    script>
    

Promise 使用

语法格式

padding:等待状态 | resolved:成功状态 | rejected:失败状态

new Promise(function (resolve, reject) {
	resolve(1);
}).then(res => {
	console.log(res);
});

每3秒输出一个数字

let p = new Promise(function (resolve, reject) {
    resolve(1);
});

p.then(res => {
    console.log(res);
    return new Promise(function (resolve, reject) {
        setInterval(function () {
            resolve(2);
        }, 3000);
    })
}).then (res => {
    console.log(res);
    return new Promise(function (resolve, reject) {
        setInterval(function () {
            resolve(3);
        }, 3000);
    })
}).then(res => {
    console.log(res);
});

async await(ES8 语法)

await 可以让异步的代码同步去写。

语法格式

async fn () {
    await this.$nextTick();
    this.$refs.ref名字.属性;
}

点击 button,隐藏 button,鼠标聚焦在 input 上(方法三:使用ES8新语法)

<template>
  <div>
      <input type="text" ref="myIpt" v-if="isShow">
      <button @click="serach" v-else>点击搜索button>
  div>
template>

<script>
export default {
    data () {
        return {
            count: 0,
            isShow: false,
        }
    },
    methods: {
        async serach () {
            this.isShow = true;
            
            await this.$nextTick();
            this.$refs.myIpt.focus();
        }
    },
}
script>

组件 name 属性

组件name可用作注册组件名字。

简单理解:可以用组件的name属性值,来注册组件名字。

export default {
  name: 'ConName',
}

App.vue

<template>
  <div>
    <ConName>ConName>
  div>
template>

<script>
import ConName from './components/MyName.vue';

export default {
  components: {
    [ConName.name]: ConName,
  }
}
script>

MyName.vue

<template>
  <div>
      <p>MyNamep>
  div>
template>

<script>
export default {
  name: 'ConName',
}
script>

你可能感兴趣的:(全栈开发学习日记,#,第八章:Vue2全家桶,javascript,前端,vue.js,ajax)