vue自2.0开始,vue-resource不再作为官方推荐的ajax方案,转而推荐使用axios。
安装axios
npm install axios
<script src="https://unpkg.com/axios/dist/axios.min.js"></script>
在src目录下的main.js里面引入axios
import axios from 'axios'
Vue.prototype.$http = axios
使用axios请求接口,在组件的 methods 中使用 this.$http命令
执行Get请求 this.$http.get('/api/user?id=1') .then(function (res) { console.log(res.data); }) .catch(function (error) { console.log(error); });
this.$http.get('/api/user', { params: { id: 1 } }) .then(function (res) { console.log(res.data); }) .catch(function (error) { console.log(error); });
执行Post,Put,Delete请求
this.$http.post('/api/user', { id: 1 sex: '男', name: '崔' }) .then(function (res) { console.log(res.data); }) .catch(function (error) { console.log(error); });