Vue learning --- based on axios in vue2

1. Axios request

This article is based on vue2.x the development environment

1.1 Network request

The axios plugin enables vue.js to send web requests and process web responses through XMLHttpRequest or JSONP.

After vue2.0, vue-resource is no longer updated, but axios is recommended.

axios is a Promise-based HTTP request client that can be used in both the browser and Node.js. It has the ability to send requests across terminals.

Before axios, fetch was also a native API to send requests through promises, and before that, requests were sent through xhr

Install via npm i axios

supported http methods

The request API of axios is designed according to the REST style, and it provides 7 kinds of request APIs:

get(url, [options])

head(url, [options])

delete(url, [options])

jsonp(url, [options])

post(url, [body], [options])

put(url, [body], [options])

patch(url, [body], [options])

Features

1. Send an XMLHttpRequest request in the browser

2. Send http request in node.js

3. Support Promise API

4. Intercept requests and responses

5. Convert request and response data

6. Cancellation request

7. Automatically convert JSON data

8. The client supports protection from CSRF/XSRF attacks

Steps for usage

Install axios: npm i axios

Introduce axios in the file to be used

import axios from ‘axios’

App.vue file:

<template>
  <!-- 一个.vue文件就是一个组件, 一个项目中只有一个根组件 App.vue -->
  <!-- 一个.vue文件内部一般是由三部分组成: template , script , style -->
  <!-- template 内部写标签 , 只能有一个根元素 -->
  <!-- script 内部写js逻辑 , 内部需要 export default {}, 所有的js代码都需要写在这里 -->
  <!-- style 内部写css样式 , 可以通过lang='xx'指定style内部的css语法 , 可以通过设置 scoped 属性 让多个.vue文件之间的样式互不影响 -->
  <div id="app">
    <div class="list">
      <h1>店铺列表</h1>
      <div class="shop" v-for="(item,index) in shoplist" :key="index">
        <div class="imgbox">
          <img :src="item.picUrl" alt="">
        </div>
        <div class="text">
          <div class="name">{
   
   {item.name}}</div>
          <div class="desc">{
   
   {item.minPriceTip}} {
   
   {item.monthSalesTip}}</div>
        </div>
      </div>
    </div>
  </div>
</template>

<script>
// 导入axios
import axios from 'axios'

export default {
  data(){
    return{
      shoplist:[]
    }
  },
  mounted(){
    // 这个方法会在组件挂载完成时自动执行,而且只执行一次
    // 发送网络请求,请求店铺列表
    axios.get('/api/shop/list').then((res)=>{
      // 保存从服务器返回的店铺列表数据,这行代码修改了data中的响应式数据,会导致当前组件更新,组件会重新渲染
      this.shoplist = res.data.list;
    })
  }
}
</script>

<style lang="scss" scoped>
.list .shop{
  display: flex;
  margin: 10px;
}
.list .shop .imgbox{
  width: 80px;
  margin-right: 10px;
}
.list .shop .imgbox img{
  width: 100%;
}
</style>

Note : As long as there is a callback function, this pointing problem will occur. Changing the callback function to an arrow function can solve this problem

Only sending requests in the App.vue file will cause cross-domain, as long as the domain name port number of the current URL is different when sending an xml request, cross-domain will appear, because the interface address in the project cannot directly send requests, and a proxy needs to be set.

To solve the cross-domain problem, write it in the vue.config.js file, and do a request forwarding in this file. After the setting is completed, you need to restart the server

Sample code:

const {
    
     defineConfig } = require('@vue/cli-service')
module.exports = defineConfig({
    
    
  transpileDependencies: true,
  devServer:{
    
     //设置开发服务器
    proxy:{
    
     //设置代理
      '/api':{
    
     //当在程序中发送以 '/api' 开头的请求时, 会自动的将请求转发到 target 所表示的目标服务器
        target:'http://waimai.yantianfeng.com/',//设置目标服务器地址
        changeOrigin:true, //允许跨域
        pathRewrite:{
    
    } //重写请求地址
      }
    }
  }
})

1.2 axios request

First import axios, write the request in mounted to receive data through the callback function, save the data of the request response to data, and solve the request cross-domain problem in the vue.config.js file.

import axios from 'axios'

export default {
    
    
  data(){
    
    
    return {
    
    
      shoplist:[]
    }
  },
  mounted(){
    
    
    // 发送不带参数的 get 请求
    // axios.get('/api/shop/list').then((res)=>{
    
    
    //   this.shoplist = res.data.list;
    // })

    // 发送带参数的 get 请求
    // axios.get('/api/shop/search',{params:{searchkey:'火锅'} }).then((res)=>{
    
    
    //   console.log(res.data);
    // })

    // 发送带参数的 post 请求
    // axios.post('/api/user/login',{ phone:'13611129070',pass:'1234' }).then((res)=>{
    
    
    //   console.log(res.data);
    // })
    
  }
}

Guess you like

Origin blog.csdn.net/m0_53181852/article/details/127598183