全局变量/模块
globalData
使用globalData
<script setup lang="ts">
onLaunch(() => {
console.log('App Launch');
});
onShow(() => {
console.log('App Show');
});
onHide(() => {
console.log('App Hide');
});
onError((err) => {
console.log('App Error:', err);
});
</script>
<script lang="ts">
export default {
globalData: {
name: 'globalData',
},
};
</script>
注意: 1. 全局
globalData不能在SFC单文件中定义; 2. 使用unplugin-auto-import插件自动导入Api
const app = getApp()
console.log(app.globalData)
getApp()
注意:
- 不要在定义于 App() 内的函数中,或调用 App 前调用 getApp() ,可以通过 this.$scope 获取对应的 app 实例
- 通过 getApp() 获取实例之后,不要私自调用生命周期函数。
- 当在首页 nvue 中使用 getApp()不一定可以获取真正的 App 对象。对此提供了 const app = getApp({allowDefault: true})用来获取原始的 App 对象,可以用来在首页对 globalData 等初始化
- 在应用 onLaunch 时,getApp 对象还未获取,暂时可以使用 this.globalData 获取 globalData
自定义全局变量模块
在utils/index.ts中定义:
export const common = {name:'global module'}
在其它页面使用:
import {common} from '@/utils'
console.log(common)
注意:如果对全局变量重新赋值要特别注意其“生命周期”,否则会造成数据丢失问题
路由参数
<navigator :url="'/pages/test/test?item='+ encodeURIComponent(JSON.stringify(item))"></navigator>
// 在页面接受参数
onLoad(option) {
const item = JSON.parse(decodeURIComponent(option.item));
}
getCurrentPages()
getCurrentPages() 函数用于获取当前页面栈的实例,以数组形式按栈的顺序给出,第一个元素为首页,最后一个元素为当前页面。
⚠️ 注意: getCurrentPages()仅用于展示页面栈的情况,请勿修改页面栈,以免造成页面状态错误。
缓存
storage 将数据存储在本地缓存中指定的 key 中,会覆盖掉原来该 key 对应的内容。(推荐优先使用异步缓存)
// 保存缓存数据
uni.setStorage({
key: 'storage_key',
data: 'hello',
success: function () {
console.log('success');
}
});
// 获取缓存数据
uni.getStorage({
key: 'storage_key',
success: function (res) {
console.log(res.data);
}
});
// 移除指定缓存数据
uni.removeStorage({
key: 'storage_key',
success: function (res) {
console.log('success');
}
});
// 清除所有缓存数据
uni.clearStorage()
状态管理
- pinia
- vuex
事件通讯
uni.$emit
uni.$emit(eventName,OBJECT)触发全局的自定义事件。附加参数都会传给监听器回调。
uni.$emit('update',{msg:'页面更新'})
uni.$on
uni.emit 触发,回调函数会接收所有传入事件触发函数的额外参数。
uni.$on('update',function(data){
console.log('监听到事件来自 update ,携带参数 msg 为:' + data.msg);
})
uni.$once
uni.once(eventName,callback)监听全局的自定义事件。事件可以由 uni.\emit 触发,但是只触发一次,在第一次触发之后移除监听器。
uni.$once('update',function(data){
console.log('监听到事件来自 update ,携带参数 msg 为:' + data.msg);
})
uni.$off
uni.$off([eventName, callback])移除全局自定义事件监听器。
Tips:
- 如果没有提供参数,则移除所有的事件监听器;
- 如果只提供了事件,则移除该事件所有的监听器;
- 如果同时提供了事件与回调,则只移除这个回调的监听器;
- 提供的回调必须跟$on 的回调为同一个才能移除这个回调的监听器;
uni.$off('update', fn)
完整事例
<script>
export default {
data() {
return {
val: 0
}
},
onLoad() {
setInterval(()=>{
uni.$emit('add', {
data: 2
})
},1000)
uni.$on('add', this.add)
},
methods: {
comunicationOff() {
uni.$off('add', this.add)
},
add(e) {
this.val += e.data
}
}
}
</script>
消息订阅
- PubSubJS PubSubJS 是一个用 JavaScript 编写的基于主题的发布/订阅库。
import PubSub from 'pubsub-js'
export const MY_TOPIC = Symbol('MY_TOPIC')
// create a function to subscribe to topics
var mySubscriber = function (msg, data) {
console.log( msg, data );
};
// add the function to the list of subscribers for a particular topic
// we're keeping the returned token, in order to be able to unsubscribe
// from the topic later on
var token = PubSub.subscribe(MY_TOPIC, mySubscriber);
// publish a topic asynchronously
PubSub.publish(MY_TOPIC, 'hello world!');
// publish a topic synchronously, which is faster in some environments,
// but will get confusing when one topic triggers new topics in the
// same execution chain
// USE WITH CAUTION, HERE BE DRAGONS!!!
PubSub.publishSync(MY_TOPIC, 'hello world!');
// unsubscribe this subscriber from this topic
PubSub.unsubscribe(token);
推荐阅读
关注我
利用空闲时间免费兼职(长期有效),请联系我(PS:关注公众号后,点击“联系我”获取联系方式)~