Skip to content

vue3全局变量

一、config.globalProperties

js
// main.js
import { createApp } from 'vue';
import App from './App.vue';

const app = createApp(App);

// 添加全局方法或属性
app.config.globalProperties.$http = (url) => {
  return fetch(url).then(res => res.json());
};

// 添加全局变量
app.config.globalProperties.$appName = 'My Awesome App';

app.mount('#app');
// main.js
import { createApp } from 'vue';
import App from './App.vue';

const app = createApp(App);

// 添加全局方法或属性
app.config.globalProperties.$http = (url) => {
  return fetch(url).then(res => res.json());
};

// 添加全局变量
app.config.globalProperties.$appName = 'My Awesome App';

app.mount('#app');

页面中使用

vue
<template>
  <div>{{ $appName }}</div>
</template>

<script setup>
// 无需导入,直接使用
const fetchData = () => {
  $http('/api/data').then(data => {
    console.log(data);
  });
};
</script>
<template>
  <div>{{ $appName }}</div>
</template>

<script setup>
// 无需导入,直接使用
const fetchData = () => {
  $http('/api/data').then(data => {
    console.log(data);
  });
};
</script>

二、Provide / Inject

js
import { createApp } from 'vue';
const globalVar = 'This is a global variable';

const app = createApp();
app.provide('globalVar', globalVar);
import { createApp } from 'vue';
const globalVar = 'This is a global variable';

const app = createApp();
app.provide('globalVar', globalVar);

页面中使用

vue
<script setup>
import { inject } from 'vue';

// 注入全局变量
const globalVar = inject('globalVar');

console.log(globalVar); // 输出: This is a global variable
</script>
<script setup>
import { inject } from 'vue';

// 注入全局变量
const globalVar = inject('globalVar');

console.log(globalVar); // 输出: This is a global variable
</script>

程序员小洛文档