vue學習七之Axios
阿新 • • 發佈:2018-11-06
JQuery時代,我們使用ajax向後臺提交資料請求,Vue時代,Axios提供了前端對後臺資料請求的各種方式。
什麼是Axios
Axios是基於Promise的Http客戶端,可以在瀏覽器和node.js中使用。
為什麼使用Axios
Axios非常適合前後端資料互動,另一種請求後端資料的方式是vue-resource,vue-resource已經不再更新了,且只支援瀏覽器端使用,而Axios同時支援瀏覽器和Node端使用。
Vue開發者推薦使用更好的第三方工具,這就是Axios,詳細的檔案,請參考Evan You的這篇文章。
安裝
Axios的安裝支援多種方式
npm安裝
1 |
npm install axios |
cdn
1 |
<script src="https://cdn.bootcss.com/axios/0.18.0/axios.min.js"></script> |
使用方式介紹
接下來,我們使用Django,搭建一個後臺程式,並使用Vue Cli搭建一個前端程式,使用Axios進行前後端資料互動。
使用Vue Cli建立一個前端程式
1 |
vue init webpack luffy_fontend |
使用Django建立一個後端程式luffy_backend
1 |
django-admin startproject luffy_backend |
建立一個courses應用
1 |
cd luffy_backend |
在models.py中建立兩個類
1 |
from django.db import models |
插入資料
1 |
// courses_courses |
在views.py中寫好介面
1 |
from django.shortcuts import render, HttpResponse |
定義介面
配置後臺介面
獲取課程資訊
1 |
<template> |
獲取學生資訊
1 |
<template> |
以上,就是我們通過Axios的get和post請求與後臺進行資料互動的全過程。