上一篇文章介紹了路由的基礎知識,我們已經學會了使用路由跳轉鏈接,當碰到更加複雜的需求的時候,可以查閱下官網api,接下來,我們需要向後臺發送請求了,由於vue不自帶ajax請求模塊,所以我們安裝官方推薦的axios的模塊
1、安裝axios
npm install axios --save
2、打開項目的main.js,添加以下代碼
//先引入模塊
import axios from 'axios'
//這句話的意思是把axios註冊到全局vue對象中去。
Vue.prototype.$ajax = axios
3、在組件中進行請求數據,如下方法
submitDate(){
let that = this;
that.$ajax({
method: 'post',
url: 'http://localhost:8082/article/add',
data: {
title: that.title,
author: that.author,
keyWord:that.keyWord,
mdValue:that.msg.mdValue,
htmlValue:that.msg.htmlValue
}
}).then(response=>{
if(response.data.c=100){
var id = response.data.insertId;
that.title='';
that.keyWord='';
that.msg.mdValue='';
//跳轉界面到首頁
router.push({ path: `/content/${id}` }); // -> /user/123
}
}).catch(err=>{
console.log(err);
});
}
在組件中進行發送請求就已經完成了,是不是非常容易配置的。
不過平時我們進行開發的時候,會使用到vuex(Vuex 是一個專爲 Vue.js 應用程序開發的狀態管理模式),我們會在action中向後臺發送請求的,由於這裏無法使用全局vue組件實例,不過可以向下面的寫法(vuex的知識可以跳過,下篇會將,只管發送axios的)
/* eslint-disable */
import axios from 'axios' //引入axios
const HOST = 'http://localhost:8082';
export default {
//初始化信息
initializeData({ commit }) {
//直接發送請求即可
axios.get(HOST+'/article/list')
.then(function (response) {
commit('INITIALIZE_DATA',response.data.list);
})
.catch(function (error) {
});
}
}
分爲兩步:
第一步:直接引入axios模塊
第二步:參照api直接發送請求即可
總結:vue項目開發中兩種使用方式的寫法都列舉出來了,還是非常簡單的。下一篇我們主要講解下vue中如何使用vuex進行狀態管理工作