vue学习(七)使用Axios实现ajax请求

axios网址:https://www.kancloud.cn/yunye/axios/234845

一、Axios安装方式

1、使用 npm:

npm install axios

在项目根目录下面执行上面的命令。

2、使用 cdn:

<script src="https://unpkg.com/axios/dist/axios.min.js"></script>

在index.html页面引入这个js。

两种方式任选其一。

二、Axios的请求方法

get请求、post请求等,请看axios网址

三、在组件中使用

1、在main.js中引入和在main.js中使用

import Vue from "vue";
import App from "./App.vue";
import axios from "axios";//引入axios

Vue.prototype.$axios = axios; // 把对象挂载vue中
Vue.config.productionTip = false;
new Vue({
  render: (h) => h(App),
  //初始化页面完成后,执行该函数
  mounted() {
    //在main.js中使用axios
    // axios get请求接口
    this.$axios.get("http://jsonplaceholder.typicode.com/todos").then((res) => {
      var todos = res.data;
      console.log(1111111 + ";" + todos);
    });
  }
}).$mount("#app");

2、在组件中使用

<template>
  <div id="app">
    <img alt="Vue logo" src="./assets/logo.png" />
    <DemoHello/>
  </div>
</template>

<script>
import DemoHello from "./components/DemoHello.vue";

export default {
  name: "App",
  components: {
    DemoHello,
  },
  //创建实列后,运行当前函数。
  created: function () {
    // axios get请求接口
    this.$axios.get("http://jsonplaceholder.typicode.com/todos").then((res) => {
      console.log(res.data);
    });
  },
};
</script>

<style>
#app {
  font-family: Avenir, Helvetica, Arial, sans-serif;
  -webkit-font-smoothing: antialiased;
  -moz-osx-font-smoothing: grayscale;
  text-align: center;
  color: #2c3e50;
  margin-top: 60px;
}
</style>

直接在方法或者函数中添加就行了。

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值