uni-app设置页面不存在时跳转到指定页面

发布于:2024-12-19 ⋅ 阅读:(10) ⋅ 点赞:(0)

使用uni-app的页面不存在事件

uni-app提供了onPageNotFound事件,可以在App.vue中监听这个事件,并在事件触发时执行跳转。

<script>
	export default {
		onLaunch: function() {
			console.log('App Launch')
		},
		onShow: function() {
			console.log('App Show')
		},
		onHide: function() {
			console.log('App Hide')
		},
        onPageNotFound: function(params) {
            console.log("params.path", params.path);
            // 使用uni.redirectTo进行无动画的页面跳转
            uni.redirectTo({
                url: '/pages/notFound/notFound'
            });
        }
	}
</script>

在index.html中添加跳转

在index.html中添加script脚本,判断当前url,如果是出错的url,则跳转到正确的url上。

<!DOCTYPE html>
<html lang="en">
  <head>
    <link rel="stylesheet" href="/assets/uni.c2b119df.css">

    <meta charset="UTF-8" />
    <script>
      var coverSupport = 'CSS' in window && typeof CSS.supports === 'function' && (CSS.supports('top: env(a)') ||
        CSS.supports('top: constant(a)'))
      document.write(
        '<meta name="viewport" content="width=device-width, user-scalable=no, initial-scale=1.0, maximum-scale=1.0, minimum-scale=1.0' +
        (coverSupport ? ', viewport-fit=cover' : '') + '" />')
    </script>
    <title>标题</title>
    <script type="module" crossorigin src="/assets/index-C9NPpYnI.js"></script>
    <link rel="stylesheet" crossorigin href="/assets/index-HKh35y-j.css">
  </head>
  <body>
    <div id="app"><!--app-html--></div>
  </body>
  <script>
        var currentUrl = window.location.href;
        if (currentUrl.includes('ceshi/ceshi')) {
            var timestamp = new Date().getTime();
            window.location.href = 'https://www.demo.com/ceshi.html?timestamp=' + timestamp;
        }
    </script>
</html>