VUE中定义全局配置方法

方法一:

main.ts中

const wsapi = "ws://localhost:8081";
const appConfig = {
  wsapi,
};

const app = createApp(App);

// Provide the appConfig as a global property
app.config.globalProperties.$appConfig = appConfig;
app.use(store)

VUE中

1、setup方法中

const $appConfig = instance.appContext.config.globalProperties.$appConfig;
console.log($appConfig.wsapi); // Access the wsapi variable
2、mounted中
mounted(){
	console.log(this.$appConfig.wsapi); // Access the wsapi variable
	const wsapi = this.$appConfig.wsapi;
},

方法二:

Vue.config.js

const { defineConfig } = require('@vue/cli-service');
const AutoImport = require('unplugin-auto-import/webpack');
const Components = require('unplugin-vue-components/webpack');

module.exports = defineConfig({
  transpileDependencies: true,
  chainWebpack: (config) => {
    // Define wsapi as a global variable
    config.plugin('define').tap((args) => {
      args[0]['process.env'].wsapi = JSON.stringify('ws://localhost:8081');
      return args;
    });
  },
});

VUE中

setup方法直接使用

console.log("processwsapi"+process.env.wsapi)
posted @ 2023-07-10 10:13  zhaogaojian  阅读(72)  评论(0编辑  收藏  举报