vue快速入门(四十三)axios模块的安装与引入

发布于:2024-04-29 ⋅ 阅读:(39) ⋅ 点赞:(0)

步骤很详细,直接上教程

上一篇

  1. 在项目目录打开终端

在这里插入图片描述

  1. 输入以下命令安装axios
npm i axios
  1. 重新打开项目即可完成按照

  2. 测试

源码

main.js

import Vue from 'vue'
import App from './App.vue'

//全局引入axios
// 引入axios
import axios from 'axios';
// 挂载到vue原型链上
Vue.prototype.axios = axios;

Vue.config.productionTip = false

new Vue({
  render: h => h(App),
}).$mount('#app')

App.vue

<template>
  <div id="app">
    <TestComponent/>
  </div>
</template>
<script>
import TestComponent from "./components/TestComponent.vue";
export default {
  name: "App",
  components: {
   TestComponent
  },
  data() {
    return {
    };
  },
  methods: {
  }
};
</script>
<style></style>

TestComponent.vue

<template>
  <div>
    <button @click="onClick">点击输出</button>
  </div>
</template>

<script>
//局部导入axxios
//import axios from 'axios'
export default {
    data() {
    return {
      list: [],
    };
  },
  methods: {
    onClick() {
        console.log(this.list);
    },
  },
  async created() {
    //全局导入了axios需要加this,局部的不用this
    const res = await this.axios.get("http://hmajax.itheima.net/api/news");

    setTimeout(() => {
      this.list = res.data.data;
    }, 2000);
  },
};
</script>

<style lang="less" scoped>
</style>

效果演示

在这里插入图片描述

🎁附加:

如何在终端关闭当前已经打开的项目

Ctrl+c,再输入y,最后回车

在这里插入图片描述