uniapp mounts the global common method main/globalData

01.main.js mounting scheme (the most commonly used):
main.js part:

// main.js
import App from './App'
import Vue from 'vue'
Vue.config.productionTip = false
App.mpType = 'app'

// 全局挂载
import $tools from './tool';
Vue.prototype.$tools = $tools;

const app = new Vue({
    
    
    ...App
})
app.$mount()

Global tools:

// tool/index.js
export default {
    
    
	aa: '8888',
	bb: () => {
    
    
		// ...
	}
}

Page reference:

<template>
	<view class="content">
		获取到:{
    
    {
    
    getAA}}
	</view>
</template>

<script>
	const app = getApp(); //同小程序app,类似vue的全局this
	console.log(app.$tools.aa); //调用方式

	export default {
    
    
		data() {
    
    
			return {
    
    
				getAA: app.$tools.aa
			}
		},
	}
</script>

<style>
	.content {
    
    
		text-align: center;
		padding-top: 30rpx;
	}
</style>

02. Borrow the globalData global object:
App.vue:

<script>
	import $tools from './tool';
	export default {
    
    
		onLaunch: function() {
    
    
			console.log('App Launch')
		},
		onShow: function() {
    
    
			console.log('App Show')
		},
		onHide: function() {
    
    
			console.log('App Hide')
		},
		globalData: {
    
    
			...$tools
		}
	}
</script>

Global tools:

// tool/index.js
export default {
    
    
	aa: '8888',
	bb: () => {
    
    
		// ...
	}
}

transfer:

<template>
	<view class="content">
		获取到:{
    
    {
    
    getAA}}
	</view>
</template>

<script>
	const app = getApp(); //同小程序app,类似vue的全局this
	console.log(app.globalData.aa); //调用方式

	export default {
    
    
		data() {
    
    
			return {
    
    
				getAA: app.globalData.aa
			}
		},
	}
</script>

03. Call directly:

<template>
	<view class="content">
		获取到:{
    
    {
    
    getAA}}
	</view>
</template>

<script>
	import $tools from '@/tool/index.js';
	console.log($tools.aa)

	export default {
    
    
		data() {
    
    
			return {
    
    
				getAA: $tools.aa
			}
		},
	}
</script>


At this point, it is basically over. The most commonly used is the first type to mount the global, and globalData is generally similar to the vuex global storage value.

Guess you like

Origin blog.csdn.net/weixin_44461275/article/details/121829441