uniapp nvue开发App 横竖屏切换丢失上下文导致 setTimeout和clearTimeout报错
报错内容如下
[JS Framework] Failed to find taskCenter (35).
[JS Framework] Failed to execute the callback function:TypeError: c.clearTimeout is not a function
reportJSException >>>> exception function:__WEEX_CALL_JAVASCRIPT__, exception:JavaScript execute error!Uncaught TypeError: c.clearTimeout is not a function
报错代码如下
<script setup lang="ts">
const videoHeight = ref(0);
const videoWidth = ref(0);
onLoad(() => {plus.screen.lockOrientation('landscape-primary');
});
function handleWindowResize(res) {videoWidth.value = res.size.windowWidth;videoHeight.value = res.size.windowHeight;
}
onMounted(() => {uni.onWindowResize(debounce(handleWindowResize, 200))
})
onBeforeUnmount(() => {uni.offWindowResize(handleWindowResize)
})// debounce函数定义
function debounce(fn: Function, wait: number) {let timer: any;return function () {timer && clearTimeout(timer);timer = setTimeout(() => {timer = false;fn.apply(this, arguments); // 把参数传进去}, wait);};
}
</script>
进入页面,切换横屏获取宽高设置video组件占满全屏,监听横竖屏切换防抖避免多次重复赋值。从开发流程上没啥问题onWindowResize和offWindowResize就是用来解决这个问题的。搜了一些帖子也没搜到相关答案,本想着实在不行就把防抖取消掉也不是不能用。今天有空翻了下官方文档看到一个没用过的 生命周期 onResize 觉得也可以解决此问题就试了一下。
改后的代码如下
<script setup lang="ts">
import { onResize } from '@dcloudio/uni-app'
const videoHeight = ref(0);
const videoWidth = ref(0);
onLoad(() => {plus.screen.lockOrientation('landscape-primary');
});
function handleWindowResize(res) {videoWidth.value = res.size.windowWidth;videoHeight.value = res.size.windowHeight;
}
onResize(debounce(handleWindowResize, 200))// debounce函数定义
function debounce(fn: Function, wait: number) {let timer: any;return function () {timer && clearTimeout(timer);timer = setTimeout(() => {timer = false;fn.apply(this, arguments); // 把参数传进去}, wait);};
}
</script>
弃用onWindowResize和offWindowResize改用生命周期,不仅更加简单方便而且解决了我的问题