Vue và Axios: Hướng dẫn sử dụng và cấu hình

Axios trong Vue.js

Axios là một thư viện HTTP dựa trên promise, có thể sử dụng trong trình duyệt và Node.js.

Tạo XMLHttpRequests từ trình duyệt Tạo http request từ node.js Hỗ trợ Promise API Chặn request và response Chuyển đổi dữ liệu request và response Hủy request Chuyển đổi JSON tự động Hỗ trợ phòng thủ XSRF trên client

Cài đặt: npm install axios --save

  1. Yêu cầu GET cơ bản

Trong file main.js:

import Vue from 'vue'
import AxiosLibrary from 'axios'

Vue.config.productionTip = false

Vue.prototype.$http = AxiosLibrary

new Vue({
  el: '#app',
  components: { App },
  template: '<App/>'
})

Trong component:

<script>
export default {
  data() {
    return {
      responseData: {}
    }
  },
  created() {
    this.$http.get("http://127.0.0.1/add/", {params: {x: "1", y: "2"}})
      .then(res => { this.responseData = res.data; })
      .catch(error => { console.log(error); })
  }
}
</script>

Hoặc sử dụng cú pháp chung:

this.$http({
  method: 'get',
  url: 'https://httpbin.org/get',
  params: {name: 'Người dùng', age: 25, gender: 'Nam'}
})
.then(res => { this.data = res.data })
.catch(error => { console.log(error) })
  1. Yêu cầu POST cơ bản

Gửi dữ liệu dạng form

this.$http.post('https://httpbin.org/post', "name=Người dùng&age=25&gender=Nam")

Hoặc sử dụng qs để chuyển đổi object thành chuỗi urlencoded:

import qs from "qs"

this.$http.post('https://httpbin.org/post', qs.stringify({name: 'Người dùng', age: '25', gender: 'Nam'}))

Cú pháp chung:

this.$http({
  method: 'post',
  url: 'https://httpbin.org/post',
  data: "name=Người dùng&age=25&gender=Nam"
})
.then(res => { this.data = res.data })
.catch(error => { console.log(error) })

Gửi yêu cầu JSON

this.$http.post('https://httpbin.org/post', {name: 'Người dùng', age: '25', gender: 'Nam'})

Hoặc:

this.$http({
  method: 'post',
  url: 'https://httpbin.org/post',
  data: {name: 'Người dùng', age: '25', gender: 'Nam'}
})
  1. Cấu hình toàn cục và bộ chặn

Cấu hình mặc định toàn cục

AxiosLibrary.defaults.baseURL = 'https://httpbin.org';
AxiosLibrary.defaults.headers.common['Authorization'] = '123';
AxiosLibrary.defaults.headers.post['x-test'] = 'abc';

Bộ chặn (Interceptors)

// Thêm bộ chặn request
AxiosLibrary.interceptors.request.use(function(config) {
    if (config.method === "post") {
        config.data = qs.stringify(config.data);
    }
    return config;
}, function(error) {
    return Promise.reject(error);
});

// Thêm bộ chặn response
AxiosLibrary.interceptors.response.use(function(response) {
    return response;
}, function(error){
    return Promise.reject(error);
});
  1. Xử lý CORS

Khi phát triển, có thể gặp lỗi CORS khi gọi API từ các domain khác. Cách giải quyết:

Cấu hình trong file config/index.js:

proxyTable: {
    "/api": {
        target: "http://api.example.com",
        changeOrigin: true,
        pathRewrite: {
            "^/api": ""
        }
    }
}

Trong file main.js:

Vue.prototype.API_HOST = '/api';

Trong component:

created() {
  const apiUrl = this.API_HOST + '/endpoint';
  this.$http.get(apiUrl)
    .then(res => { this.data = res.data })
    .catch(error => { console.log(error) })
}
  1. Thao tác với DOM gốc

Sử dụng ref trong Vue

<template>
  <div id="app">
    <p ref="myParagraph">Nội dung</p>
  </div>
</template>

<script>
export default {
  mounted() {
    this.$refs.myParagraph.innerHTML = 'Nội dung mới';
    this.$refs.myParagraph.style.color = 'blue';
    this.$refs.myParagraph.addEventListener("click", () => {
      console.log('Đã click');
    });
  }
}
</script>

Sử dụng jQuery

Cài đặt: npm install --save jquery

<template>
  <div id="app">
    <p id="myParagraph">Nội dung</p>
  </div>
</template>

<script>
import $ from "jquery"

export default {
  mounted() {
    $('#myParagraph').css("color", "red");
  }
}
</script>

Thẻ: Vue.js Axios http JavaScript Web Development

Đăng vào ngày 27 tháng 6 lúc 13:39