Home > Web Front-end > uni-app > How to define variables globally in uniapp

How to define variables globally in uniapp

coldplay.xixi
Release: 2023-01-13 00:44:08
Original
10259 people have browsed it

Uniapp's method of defining global variables: 1. Use a public module, the code is [return obj instanceof Array]; 2. Directly extend some frequently used constants or methods to [Vue.prototype] .

How to define variables globally in uniapp

The operating environment of this tutorial: windows7 system, uni-app2.5.1 version, Dell G3 computer. This method is suitable for all brands of computers.

Recommendation (free): uni-app development tutorial

How to define global variables in uniapp:

1. Public module

Define a dedicated module to organize and manage these global variables and introduce them on the required pages.

Note that this method only supports sharing between multiple vue pages or multiple nvue pages, but not between vue and nvue.

The example is as follows:

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 common 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  
}
Copy after login

Next, reference the module in pages/index/index.vue

<script>  
    import helper from &#39;../../common/helper.js&#39;;  
    export default {  
        data() {  
            return {};  
        },  
        onLoad(){  
            console.log(&#39;now:&#39; + helper.now());  
        },  
        methods: {  
        }  
    }  
</script>
Copy after login

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

2. Mount Vue.prototype

Extend some frequently used constants or methods directly to Vue.prototype, and each Vue object will " "Inherit".

Note that this method only supports vue pages

The example is as follows:

Mount properties/methods in main.js

Vue.prototype.websiteUrl = &#39;http://uniapp.dcloud.io&#39;;  
Vue.prototype.now = Date.now || function () {  
    return new Date().getTime();  
};  
Vue.prototype.isArray = Array.isArray || function (obj) {  
    return obj instanceof Array;  
};
Copy after login

Then in pages/ This method of calling

<script>  
    export default {  
        data() {  
            return {};  
        },  
        onLoad(){  
            console.log(&#39;now:&#39; + this.now());  
        },  
        methods: {  
        }  
    }  
</script>
Copy after login

in index/index.vue only needs to be defined in main.js and can be called directly in each page.

Tips

  • Do not have duplicate attribute or method names in each page.

  • It is recommended that the properties or methods mounted on Vue.prototype can be added with a unified prefix. For example, $url and global_url are easy to distinguish from the content of the current page when reading the code.

3. globalData

There is a globalData concept in the applet, and global variables can be declared on the App. Vue did not have this kind of concept before, but uni-app introduced the globalData concept and implemented it on platforms including H5 and App.

You can define globalData in App.vue, or you can use the API to read and write this value.

  • globalData supports vue and nvue shared data.

  • globalData is a relatively simple way to use global variables.

Definition: App.vue

<script>  
    export default {  
        globalData: {  
            text: &#39;text&#39;  
        },  
        onLaunch: function() {  
            console.log(&#39;App Launch&#39;)  
        },  
        onShow: function() {  
            console.log(&#39;App Show&#39;)  
        },  
        onHide: function() {  
            console.log(&#39;App Hide&#39;)  
        }  
    }  
</script>  
<style>  
    /*每个页面公共css */  
</style>
Copy after login


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 bind the globalData data to the page, you can reassign the variable in the onshow declaration cycle of the page. Starting from HBuilderX 2.0.3, nvue pages also support onshow in uni-app compilation mode.

4. 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.

Here is an example of synchronously updating user information after logging in to briefly explain the usage of Vuex. For more detailed Vuex content, it is recommended to go to its official website Vuex to learn.

Example:

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

const store = new Vuex.Store({  
    state: {  
        login: false,  
        token: &#39;&#39;,  
        avatarUrl: &#39;&#39;,  
        userName: &#39;&#39;  
    },  
    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 = &#39;&#39;;  
            state.userName = &#39;&#39;;  
            state.avatarUrl = &#39;&#39;;  
        }  
    }  
})
Copy after login

Then, you need to create a new store directory in the main directory .js mount Vuex

import store from &#39;./store&#39;  
Vue.prototype.$store = store
Copy after login

Finally, use

<script>  
    import {  
        mapState,  
        mapMutations  
    } from &#39;vuex&#39;;  
    export default {  
        computed: {  
            ...mapState([&#39;avatarUrl&#39;, &#39;login&#39;, &#39;userName&#39;])  
        },  
        methods: {  
            ...mapMutations([&#39;logout&#39;])  
        }  
    }  
</script>
Copy after login

in pages/index/index.vue Related free learning recommendations: Programming Video

The above is the detailed content of How to define variables globally in uniapp. For more information, please follow other related articles on the PHP Chinese website!

Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template