4 ways to implement uni-app global variables

1. Common modules

Define a dedicated module to organize and manage these global variables, and introduce them on the required pages.
Examples are as follows:

1. Create a common directory in the root directory of the uni-app project, and then create a new helper.js in the common directory to define public methods.

const websiteUrl = 'http://uniapp.dcloud.io';  
const now = Date.now || function () {
    
      
    return new Date().getTime();  
};  
const isArray = Array.isArray || function (obj) {
    
      
    return obj instanceof Array;  
};  

export default {
    
      
    websiteUrl,  
    now,  
    isArray  
}

2. Reference the module in pages/index/index.vue

<script>  
    import helper from '../../common/helper.js';  

    export default {
    
      
        data() {
    
      
            return {
    
    };  
        },  
        onLoad(){
    
      
            console.log('now:' + helper.now());  
        },  
        methods: {
    
      
        }  
    }  
</script>

This method is more convenient to maintain, but the disadvantage is that it needs to be introduced every time.

2. Vuex

Vuex is a state management pattern developed specifically for Vue.js applications. It uses centralized storage to manage the state of all components of the application, and uses corresponding rules to ensure that the state changes in a predictable way.
HBuilderX 2.2.5+ onwards, supports sharing between vue and nvue

1. Create a new store directory in the root directory of the uni-app project, and create index.js in the store directory to define the status value.

const store = new Vuex.Store({
    
      
    state: {
    
      
        login: false,  
        token: '',  
        avatarUrl: '',  
        userName: ''  
    },  
    mutations: {
    
      
        login(state, provider) {
    
      
            console.log(state)  
            console.log(provider)  
            state.login = true;  
            state.token = provider.token;  
            state.userName = provider.userName;  
            state.avatarUrl = provider.avatarUrl;  
        },  
        logout(state) {
    
      
            state.login = false;  
            state.token = '';  
            state.userName = '';  
            state.avatarUrl = '';  
        }  
    }  
})

2. Mount Vuex in main.js

import store from './store'  
Vue.prototype.$store = store

3. Use in pages/index/index.vue

<script>  
    import {
    
      
        mapState,  
        mapMutations  
    } from 'vuex';  

    export default {
    
      
        computed: {
    
      
            ...mapState(['avatarUrl', 'login', 'userName'])  
        },  
        methods: {
    
      
            ...mapMutations(['logout'])  
        }  
    }  
</script>

Example steps:
If you are not logged in, you will be prompted to log in. After jumping to the login page, click "Login" to obtain the user information. After synchronizing the updated status, return to the personal center to see the results of the information synchronization.

Note: Compared with the previous method, this method is more suitable for handling global situations where the value will change.

3. Mount to Vue.prototype

Extend some frequently used constants or methods directly to Vue.prototype, and each Vue object will "inherit" them.
注意这种方式只支持vue页面
Examples are as follows:

1. Mount properties/methods in main.js

Vue.prototype.websiteUrl = 'http://uniapp.dcloud.io';  
Vue.prototype.now = Date.now || function () {
    
      
    return new Date().getTime();  
};  
Vue.prototype.isArray = Array.isArray || function (obj) {
    
      
    return obj instanceof Array;  
};

2. Call in pages/index/index.vue

<script>  
    export default {
    
      
        data() {
    
      
            return {
    
    };  
        },  
        onLoad(){
    
      
            console.log('now:' + this.now());  
        },  
        methods: {
    
      
        }  
    }  
</script>

In this way, it only needs to be defined in main.js and can be called directly in each page.

-Tips

  • Do not have duplicate property or method names on each page.
  • It is recommended Vue.prototypeto add a unified prefix to the attributes or methods mounted on. For example $url, global_urlin this way, it is easy to distinguish it from the content of the current page when reading the code.

4. globalData

There is a globalData concept in the mini program, and global variables can be declared on the App. Vue did not have this kind of concept before, but uni-app introduced the concept of globalData and implemented it on platforms including H5 and App.
You can define globalData in App.vue, and you can also use the API to read and write this value.

globalData supports shared data between vue and nvue.

globalData is a relatively simple way to use global variables.

1.Definition: App.vue

<script>  
    export default {
    
      
        globalData: {
    
      
            text: 'text'  
        },  
        onLaunch: function() {
    
      
            console.log('App Launch')  
        },  
        onShow: function() {
    
      
            console.log('App Show')  
        },  
        onHide: function() {
    
      
            console.log('App Hide')  
        }  
    }  
</script>  

<style>  
    /*每个页面公共css */  
</style>  

2. The way to operate globalData in js is as follows:

Assignment:getApp().globalData.text = 'test'

Value:console.log(getApp().globalData.text) // 'test'

If you need to globalDatabind the data to the page, you can onshowreassign the variable in the page's declaration cycle.HBuilderX 2.0.3起,nvue页面在uni-app编译模式下,也支持onshow。

Several ways to use uni-app global variables

Guess you like

Origin blog.csdn.net/qq_40660283/article/details/130525140
Recommended