zoukankan      html  css  js  c++  java
  • Vue 3.x 全局引入axios 方法

    vue 全局引入 axios 大概会在网上找到下面两种方案:

    一、改写Vue的原型属性

    方法是在main.js中写入

    import { createApp } from 'vue'
    import App from './App.vue'
    import axios from 'axios'
    const app = createApp(App)
    app.prototype.$http= axios
    

    经过踩坑,发现vue3.0取消了Vue.prototype,官方文档推荐使用globalProperties
    于是main.js改写成

    import { createApp } from 'vue'
    import App from './App.vue'
    import axios from 'axios'
    const app = createApp(App)
    app.config.globalProperties.$http = axios
    

    然后在组件中引用

    this.$http.get('api/getNewsList')
    .then((response)=>{
        console.log(response)
    })
    

    继续踩坑
    图片名称

    vue3.0中是没有this的。使用getCurrentInstance来获取上下文
    const { proxy } = getCurrentInstance() 这里的proxy相当于this

    const { proxy } = getCurrentInstance()
    proxy.$http.get('api/getNewsList')
    .then((response)=>{
        console.log(response)
    })
    

    二、使用vue-axios插件

    首先在主入口文件main.js中引用:

    import { createApp } from 'vue'
    import App from './App.vue'
    import axios from 'axios'
    import VueAxios from 'vue-axios'
    const app = createApp(App)
    app.use(VueAxios,axios);
    

    然后在组件中引用,注意vue3.x没有this

    axios.get('api/getNewsList')
    .then((response)=>{
        console.log(response)
    })
    

    文章来自 Yongchin'blog yongchin.xyz

  • 相关阅读:
    Oracle,第六周
    JAVA创建对象的几种方式
    深拷贝和浅拷贝
    Facade
    Adapter
    低谷过去了
    Oracle,第五周
    Command
    Singleton
    mybatis自动生成mapping和实体
  • 原文地址:https://www.cnblogs.com/semishigure/p/14705215.html
Copyright © 2011-2022 走看看