1、axios简介

axios是基于promise的网络请求

2、axios安装

  1. npm install --save axios
  2. //用于将post请求中的data对象转化为字符串
  3. npm install --save querystring

3、axios使用

在要进行网络请求的组件中进行导入:
import axios from ‘axios’
比如在MyCustomComponent.vue文件中进行导入使用:

  1. <template>
  2. <div>
  3. <p>{{ chengpin.title }}</p>
  4. </div>
  5. </template>
  6. <script>
  7. import axios from "axios"
  8. import querystring from "querystring"
  9. export default {
  10. name: "MyCustomComponent",
  11. data() {
  12. return {
  13. chengpin: {}
  14. }
  15. },
  16. mounted() {
  17. // get请求方式
  18. axios({
  19. method: "get",
  20. url: "http://iwenwiki.com/api/blueberrypai/getChengpinDetails.php"
  21. }).then(res => {
  22. this.chengpin = res.data.chengpinDetails[0];
  23. })
  24. // 快捷get请求
  25. axios.get("http://iwenwiki.com/api/blueberrypai/getChengpinDetails.php").then(res => {
  26. console.log("--------快捷get请求--------");
  27. console.log(res.data);
  28. })
  29. // post请求方式
  30. axios({
  31. method: "post",
  32. url: "http://iwenwiki.com/api/blueberrypai/login.php",
  33. data: querystring.stringify({
  34. user_id: "iwen@qq.com",
  35. password: "iwen123",
  36. verification_code: "crfvw"
  37. })
  38. }).then(res => {
  39. console.log("--------post请求方式--------");
  40. console.log(res.data);
  41. })
  42. // 快捷post请求
  43. axios.post("http://iwenwiki.com/api/blueberrypai/login.php", querystring.stringify({
  44. user_id: "iwen@qq.com",
  45. password: "iwen123",
  46. verification_code: "crfvw"
  47. })
  48. ).then(res => {
  49. console.log("--------快捷post请求--------");
  50. console.log(res.data);
  51. })
  52. }
  53. }
  54. </script>
  55. <style scoped>
  56. </style>

App.vue

  1. <template>
  2. <MyComponent/>
  3. </template>
  4. <script>
  5. import MyComponent from './components/MyCustomComponent.vue'
  6. export default {
  7. name: 'App',
  8. data(){
  9. return {
  10. }
  11. },
  12. components: {
  13. MyComponent
  14. }
  15. }
  16. </script>
  17. <style>
  18. *{
  19. margin: 0px;
  20. padding: 0px;
  21. }
  22. #app {
  23. font-family: Avenir, Helvetica, Arial, sans-serif;
  24. -webkit-font-smoothing: antialiased;
  25. -moz-osx-font-smoothing: grayscale;
  26. text-align: center;
  27. color: #2c3e50;
  28. }
  29. </style>

效果:
image.png