Vue.prototype全局属性

Mr.PDG小于 1 分钟Vue3Vue.prototypeglobalProperties

vue2

vue2中可以通过Vue.prototype来定义全局属性,在组件中可以通过this来访问这些属性。

// main.js
Vue.prototype.$http = axios
<script>
export default {
  mounted() {
    this.$http.get('/api').then(res => {
      console.log(res)
    })
  }
}
</script>

vue3

vue3中Vue.prototype被废弃了,取而代之的是app.config.globalProperties,用法如下:

// main.js
app.config.globalProperties.msg = 'hello'
<script setup>
const { proxy } = getCurrentInstance()

console.log(proxy.msg) // hello
</script>