Search code examples
javascriptvuejs3vue-options-api

Vue 3's Provide / Inject using the Options API


I've been trying to follow the documentation for the API on the Vue 3 website which says to use app.provide('keyName',variable) inside your main.js file like so:

import App from './App.vue'
import { createApp } from 'vue'
import axios from 'axios'

const app = createApp(App)

app.provide('axios', axios)

app.use('Vue')
app.mount('#app')

Then inject and use it in your child component like so:

export default {
  inject: ['axios'],
  ...
  createUser (data) {
    return this.axios.post('/users', data)
  }
}

However doing so just gives me this error in my console:

Uncaught TypeError: Cannot read properties of undefined (reading 'post')

Is there anything I'm missing? I didn't see any about an import unless you're using the Composition API. Can provide / inject be called from within a .js file? I would expect so as long as its within a export default {} statement

Ive tried following the API to a "T" but it simply refuses to work for me. Also tried searching the web for solutions but everything I've found says what I'm doing should be working just fine.


Solution

  • It works, see the playground.

    But is not absolutely necessary, since with the browser library version axios is globally defined and could be accessed also without inject

    You could also save yourself some time with the vue-axios plugin.

    Example

    const { createApp } = Vue;
    
    const myComponent = {
      inject: ['axios'],
      created() {    
        this.axios.get('/')
          .then(function (response) {
            console.log(response);
          })
         .catch(function (error) {
            console.log(error);
          })
      },
      template: '<div>My Component</div>'
    }
    
    const App = {
      components: { 
        myComponent
      }
    }
    
    const app = createApp(App)
    app.provide('axios', axios)
    app.mount('#app')
    <div id="app">  
      <my-component></my-component>
    </div>
    <script src="https://unpkg.com/vue@3/dist/vue.global.js"></script>
    <script src="https://unpkg.com/[email protected]/dist/axios.min.js"></script>