uniapp挂载全局常用方法main/globalData
01.main.js挂载方案(最常用):main.js部分:// main.jsimport App from './App'import Vue from 'vue'Vue.config.productionTip = falseApp.mpType = 'app'// 全局挂载import $tools from './tool';Vue.prototype.$tools = $tools;c
·
01.main.js挂载方案(最常用):
main.js部分:
// 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()
全局工具:
// tool/index.js
export default {
aa: '8888',
bb: () => {
// ...
}
}
页面引用:
<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.借用globalData全局对象:
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>
全局工具:
// tool/index.js
export default {
aa: '8888',
bb: () => {
// ...
}
}
调用:
<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.直接调用:
<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>
到此,基本上就结束了。常用的就是第一种挂载全局,globalData一般是类似vuex全局储存值。
更多推荐
已为社区贡献14条内容
所有评论(0)