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

  • 相关阅读:
    PHP多条件模糊查询
    纯干货!一款APP从设计稿到切图过程全方位揭秘(转)
    0532. K-diff Pairs in an Array (M)
    0933. Number of Recent Calls (E)
    0139. Word Break (M)
    0713. Subarray Product Less Than K (M)
    0399. Evaluate Division (M)
    0495. Teemo Attacking (M)
    0179. Largest Number (M)
    0389. Find the Difference (E)
  • 原文地址:https://www.cnblogs.com/semishigure/p/14705215.html
Copyright © 2011-2022 走看看