我们在用 uni-app 开发前端应用时,页面跳转是必不可少的。页面跳转主要包含应用内跳转(站内跳转)和应用外跳转(外部跳转)。下面我们一起来看看具体实现方式。

站内跳转

站内跳转主要有两种实现方式,可以通过组件和 API 接口方式实现。

采用 navigator 组件

<template>
    <view>
        <navigator url="/pages/view/view?id=1" open-type="navigate">
            <button type="default">跳转到新页面</button>
        </navigator>
    </view>
</template>

采用 API 接口

<template>
    <view>
        <button type="default" @tap="toView">跳转到新页面</button>
    </view>
</template>

<script>
    export default {
        methods: {
            toView () {
                uni.navigateTo({
                    url: '/pages/view/view?id=1'
                })
            }
        }
    }
</script>

open-type 主要有效值与 API 的对应关系

对应 API说明
navigateuni.navigateTo保留当前页面,跳转到应用内的某个页面
redirectuni.redirectTo关闭当前页面,跳转到应用内的某个页面
switchTabuni.switchTab跳转到 tabBar 页面,并关闭其他所有非 tabBar 页面
reLaunchuni.reLaunch关闭所有页面,打开到应用内的某个页面
navigateBackuni.navigateBack关闭当前页面,返回上一页面或多级页面

更多规则可查看:官方文档

目标页面参数接收:

<script>
    export default {
        onLoad: function (option) { // option为object类型,会序列化上个页面传递的参数
            console.log(option.id) // 打印出上个页面传递的参数。
        }
    }
</script>

外部跳转

外部跳转直接可以使用 web-view 组件,会自动铺满整个页面。

步骤1:在项目根路径下的 pages 目录下,新建一个页面,用于专门放置外部网站

<template>
    <web-view :src="url"></web-view>
</template>
 
<script>
    export default {
        data() {
            return {
                url: null  //要打开的外部链接
            }
        },
        onLoad: function (option) {
            this.url = option.url
        }
    }
</script>

步骤2:配置 pages.json

{
    "pages": [
        ……,
        {
            "path": "pages/web-view/web-view",
                "style": {
                    "navigationBarTitleText": "页面标题"
                }
            }
        }
    ]
}

步骤3:在需要跳转的页面,通过 navigator 组件或 API 进行跳转

<template>
    <view>
        <navigator url="/pages/web-view/web-view?url=https://www.baidu.com/">访问百度</navigator>
    </view>
</template>
如果觉得我的文章对你有用,请点个赞