Vue3 adds public methods to the global (per instance)

As we all know, vue3 will not expose Vue objects for you to use now!

So how to add public methods to each of its subcomponent instances?

For example, we need to add the $axios method to each instance

The method of adding vue2 is very simple

import View from 'view'

import axios from 'axios'

Vue.prototype.$axios = axios

 Three ways to add public methods in vue3

The first one: use app.config.globalProperties to add

import { createApp } from 'vue'
import axios from 'axios'

const app = createApp({
  created() {
     console.log(this.$axios)
  }
})

app.config.globalProperties.$axios = axios

window.vm = app.mount('#root')

 The second: use app.mixin to add

import { createApp} from 'vue'
import axios from 'axios'

const app = createApp({
  created() {
    console.log(this.$axios)
  }
})

app.mixin({
  methods: {
    $axios: axios
  }
})

window.vm = app.mount('#root')

The third method: use provide, inject method

It should be noted that this method needs to build inject and inject it into the component before it can be used

import { createApp } from 'vue'
import axios from 'axios'

const app = createApp({
  inject: ['$axios'],
  created() {
    console.log(this.$axios)
  }
})

app.provide('$axios', axios)

window.vm = app.mount('#root')

 

 

Guess you like

Origin blog.csdn.net/weixin_42335036/article/details/109223131