Public Method in Vue3

  1. app.config.globalProperties Global Property
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
// main.js Regist
import { createApp } from 'vue'
import axios from 'axios'


const app = createApp({
created() {
console.log(this.$axios)
}
})
app.config.globalProperties.$axios = axios
app.mount('#root')

// App.vue Usage
<script setup>
import {getCurrentInstance} from 'vue'
const { proxy } = getCurrentInstance(); //获取公用方法proxy.$axios
const {$axios}=proxy
console.log($axios)
</script>
  1. mixin

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    import { createApp} from 'vue'
    import axios from 'axios'

    const app = createApp({
    created() {
    console.log(this.$axios)
    }
    })
    app.mixin({
    methods: {
    $axios: axios
    }
    })
    app.mount('#root')
  2. provide, inject

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    import { createApp } from 'vue'
    import axios from 'axios'


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

本文作者: 孟 虎
本文链接: https://menghu1994.github.io/blog/2023/10/Vue/publicMethod/
版权声明: 本博客所有文章除特别声明外,均采用 CC BY-SA 4.0 协议 ,转载请注明出处!