下載axios
開發版本:axios.js
生產版本:axios.min.js
搭建服務器:json-server
- npm i -g json-server
- json-server --watch db.json(啟動服務并讀取文件,db.json文件目錄下啟動)
json-server --watch db.json --port 3000(指定端口) - 訪問:
http://localhost:3000(首頁)
http://localhost:3000/posts(讀取文件所有數據)
http://localhost:3000/posts/1(讀取id為1的數據) - db.json
{"posts" : [{"title" : "title1","anthor" : "anthor1","id" : 1},{"title" : "title2","anthor" : "anthor2","id" : 2}]
}
基本使用
<script src="../axios.js"></script>
<script src="../vue.js"></script>
<div id="app1"><button @click="search">get</button><button @click="add">add</button><ol><li v-for="item in postList" :key="item.id">{{item.title}} {{item.author}}<button @click="remove(item.id)">delete</button></li></ol>
</div>
<script>// 設置urlaxios.defaults.baseURL = "http://localhost:3000";new Vue({el:'#app1', data : {postList : []},methods : {search(){axios.get('/posts').then(res => {console.log(res);// 請求成功this.postList = res.data;}).catch(reason => {console.log(reason);// 請求失敗});},add(){axios.post('/posts',{title : "add",author : "zhangsan"}).then(res => {console.log(res);}).catch(reason => {console.log(reason);});},// 異步寫法async remove(id){try{await axios.delete('/posts/' + id);}catch (e) {console.log(e);}}}});
</script>