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>
直接在方法或者函数中添加就行了。
本文详细介绍了如何在Vue.js项目中安装和使用Axios库进行HTTP请求,包括通过npm安装、在main.js中全局挂载以及在组件内部调用API的方法。示例展示了在创建实例后如何发起GET请求,并在组件的created或mounted钩子中处理响应数据。
713

被折叠的 条评论
为什么被折叠?



