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

How to define variables globally in uniapp

Dec 08, 2020 pm 02:12 PM
uniapp global variables

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!

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

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

What is the difference between local variables and global variables of a C++ function? What is the difference between local variables and global variables of a C++ function? Apr 19, 2024 pm 03:42 PM

The difference between C++ local variables and global variables: Visibility: Local variables are limited to the defining function, while global variables are visible throughout the program. Memory allocation: local variables are allocated on the stack, while global variables are allocated in the global data area. Scope: Local variables are within a function, while global variables are throughout the program. Initialization: Local variables are initialized when a function is called, while global variables are initialized when the program starts. Recreation: Local variables are recreated on every function call, while global variables are created only when the program starts.

How to start preview of uniapp project developed by webstorm How to start preview of uniapp project developed by webstorm Apr 08, 2024 pm 06:42 PM

Steps to launch UniApp project preview in WebStorm: Install UniApp Development Tools plugin Connect to device settings WebSocket launch preview

Which one is better, uniapp or mui? Which one is better, uniapp or mui? Apr 06, 2024 am 05:18 AM

Generally speaking, uni-app is better when complex native functions are needed; MUI is better when simple or highly customized interfaces are needed. In addition, uni-app has: 1. Vue.js/JavaScript support; 2. Rich native components/API; 3. Good ecosystem. The disadvantages are: 1. Performance issues; 2. Difficulty in customizing the interface. MUI has: 1. Material Design support; 2. High flexibility; 3. Extensive component/theme library. The disadvantages are: 1. CSS dependency; 2. Does not provide native components; 3. Small ecosystem.

What development tools do uniapp use? What development tools do uniapp use? Apr 06, 2024 am 04:27 AM

UniApp uses HBuilder

What are the disadvantages of uniapp What are the disadvantages of uniapp Apr 06, 2024 am 04:06 AM

UniApp has many conveniences as a cross-platform development framework, but its shortcomings are also obvious: performance is limited by the hybrid development mode, resulting in poor opening speed, page rendering, and interactive response. The ecosystem is imperfect and there are few components and libraries in specific fields, which limits creativity and the realization of complex functions. Compatibility issues on different platforms are prone to style differences and inconsistent API support. The security mechanism of WebView is different from native applications, which may reduce application security. Application releases and updates that support multiple platforms at the same time require multiple compilations and packages, increasing development and maintenance costs.

What basics are needed to learn uniapp? What basics are needed to learn uniapp? Apr 06, 2024 am 04:45 AM

uniapp development requires the following foundations: front-end technology (HTML, CSS, JavaScript) mobile development knowledge (iOS and Android platforms) Node.js other foundations (version control tools, IDE, mobile development simulator or real machine debugging experience)

What is the difference between uniapp and flutter What is the difference between uniapp and flutter Apr 06, 2024 am 04:30 AM

UniApp is based on Vue.js, and Flutter is based on Dart. Both support cross-platform development. UniApp provides rich components and easy development, but its performance is limited by WebView; Flutter uses a native rendering engine, which has excellent performance but is more difficult to develop. UniApp has an active Chinese community, and Flutter has a large and global community. UniApp is suitable for scenarios with rapid development and low performance requirements; Flutter is suitable for complex applications with high customization and high performance.

Which is better, uniapp or native development? Which is better, uniapp or native development? Apr 06, 2024 am 05:06 AM

When choosing between UniApp and native development, you should consider development cost, performance, user experience, and flexibility. The advantages of UniApp are cross-platform development, rapid iteration, easy learning and built-in plug-ins, while native development is superior in performance, stability, native experience and scalability. Weigh the pros and cons based on specific project needs. UniApp is suitable for beginners, and native development is suitable for complex applications that pursue high performance and seamless experience.

See all articles