How to define variables globally in uniapp
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] .
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 }
Next, 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. 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 = '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; };
Then in pages/ This method of calling
<script> export default { data() { return {}; }, onLoad(){ console.log('now:' + this.now()); }, methods: { } } </script>
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: 'text' }, onLaunch: function() { console.log('App Launch') }, onShow: function() { console.log('App Show') }, onHide: function() { console.log('App Hide') } } </script> <style> /*每个页面公共css */ </style>
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: '', 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 = ''; } } })
Then, you need to create a new store directory in the main directory .js mount Vuex
import store from './store' Vue.prototype.$store = store
Finally, use
<script> import { mapState, mapMutations } from 'vuex'; export default { computed: { ...mapState(['avatarUrl', 'login', 'userName']) }, methods: { ...mapMutations(['logout']) } } </script>
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!

Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

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

Hot Article

Hot Tools

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

Hot Topics

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.

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

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.

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.

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)

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.

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.
