Several common ways to define global variables in Vue projects

In the Vue project, we need to use many variables to maintain the flow and status of data. These variables can be local variables, component variables, parent-child component variables, etc., but these variables have limitations. In some scenarios, you may need to share a variable among multiple components, in which case global variables come in handy.

How to define global variables
1. Use Vue.prototype to define global variables

By defining a property on vue's prototype, it can be accessed in all components.

  • Define global variables in main.js
// main.js
Vue.prototype.baseUrl = "https://www.example.com/api"
  • Use in the page
<template>
  <div>
    {
   
   {baseUrl}}
  </div>
</template>
  • used in method
<script>
created() {
    console.log(this.baseUrl)
},
</script>
2. Use env file to define global variables

Create an .env file in the root directory of the Vue project to store some global variables.

  • Defined in .env file
VUE_APP_BASE_URL = "https://www.example.com/api"
  • used in method
<script>
created() {
    const baseUrl = process.env.VUE_APP_BASE_URL
    console.log(baseUrl)
},
</script>
3. Use vuex to define global variables

vuex is Vue's official state management library and can be used to manage global state.

  • Define global variables
//store/index.js
export default new Vuex.Store({
  state: {
    baseUrl: "https://www.example.com/api"
  },
})
  • Use in the page
<template>
  <div>
    {
   
   {this.$store.state.baseUrl}}
  </div>
</template>
  • used in method
<script>
created() {
    const baseUrl = this.$store.state.baseUrl
    console.log(baseUrl)
},
</script>
4. Use Vue.mixin to define global variables

Through mixin, some common properties or methods can be mixed into all components.

  • Create a js file with global variables. The sample file path is: ./utils/globalVar.js
//globalVar.js
export default {
    data() {
        return {
            baseUrl: "https://www.example.com/api"
        };
    }
}
  • Introduce the globalVar.js file into the project's main.js file and use the Vue.mixin() method to mix it globally:
//main.js
import globalVar from './utils/globalVar.js'
Vue.mixin(globalVar)
  • Use in the page
<template>
  <div>
    {
   
   {baseUrl}}
  </div>
</template>
  • used in method
<script>
created() {
    console.log(this.baseUrl)
},
</script>
5. Use localStorage or sessionStorage to define global variables

A variable can be shared across all components by storing it in localStorage or sessionStorage.

  • Defined in main.js
localStorage.setItem("baseUrl", "https://www.example.com/api")
  • used in method
<script>
created() {
    const baseUrl = localStorage.getItem("baseUrl")
    console.log(baseUrl)
},
</script>
6. Configure globalProperties in vue3

vue3 provides special public data configuration methods: globalProperties, getCurrentInstance

  • Defined in main.js
//main.js
import { createApp } from 'vue'
import App from './App.vue'
const app=createApp(App)
app.config.globalProperties.baseUrl = "https://www.example.com/api"
app.mount('#app')
  • Use in the page
<template>
  <div>
    {
   
   {baseUrl}}
  </div>
</template>
  • used in method
<script setup>
import { getCurrentInstance } from "vue"
const { proxy } = getCurrentInstance()
console.log(proxy.baseUrl)
</script>
7. Automatically configure package version date

In the process of front-end development, I always encounter the situation that after the front-end package is deployed, I don’t know whether it was successful or whether the original package was replaced. I can’t tell when the package was installed. We can output a packaged date to the console. This makes it easy to distinguish the version date of the front-end package.

7.1. Vue3 defines environment variables in vite.config.js. Get the current packaging date and time.
  • Configure in vite.config.js
//vite.config.js
process.env.VITE_APP_VERSION = JSON.stringify(new Date().toLocaleString())
  • Print in App.vue
<script setup>
    console.log(import.meta.env.VITE_APP_VERSION)
</script>
7.2. vue2 defines environment variables in vue.config.js. Get the current packaging date and time.
  • Configure in vue.config.js
//vue.config.js
const webpack = require('webpack');
module.exports = {
  configureWebpack: {
    plugins: [
     new webpack.DefinePlugin({
       "process.env.VERSION": JSON.stringify(new Date().toLocaleString())
     })
   ]
  }
}
  • Print in App.vue
<script>
created() {
    console.log(process.env.VERSION)
},
</script>

Guess you like

Origin blog.csdn.net/shanghai597/article/details/134201942