页面跳转

页面跳转其实就是 HTML 的超链接,在 uni-app 中不能使用 a 标签进行页面跳转。uni-app 中有两种页面跳转的方法。

  • 使用 navigator 标签。

  • 在事件中使用链式编程跳转。

网址跳转

先看页面跳转的第一种形式,使用 navigator 标签,跳转的时候分 3 种模式。

  • 跳转到新页面后保留原页面,单击 “返回” 按钮,可以返回原页面。

  • 跳转到 tabBar 页面。

  • 关闭当前页面后再跳转到新页面,无 “返回” 按钮。

代码如下。

<template>
    <view class="content">
<!--默认跳转有历史记录,可以返回当前页面-->
        <navigator url="../detail/detail">商品详情</navigator>
<!--open-type="switchTab" 跳转到tabBar页面-->
        <navigator url="../login/login" open-type="switchTab">登录页面</navigator>
<!-- open-type="redirect" 清除历史记录,不能返回当前页面 -->
        <navigator url="../detail/detail" open-type="redirect">商品详情</navigator>
    </view>
</template>

代码解析如下。

  • 通过 open-type 设置跳转模式,默认可以返回当前页面。

  • open-type="switchTab" 表示跳转到 tabBar 页面。

  • open-type="redirect" 表示无历史记录跳转。

事件跳转

通过事件进行页面跳转,同样分为 3 种情况。

(1)有历史记录,可返回当前页面,使用 uni.navigateTo 方法,代码如下。

export default {
    methods: {
        go() {
            uni.switchTab({
                url: '../login/login'
            })
        },
    }
}

(2)跳转到 tabBar 页面,使用 uni.switchTab 方法,代码如下。

<template>
    <view class="content">
        <button type="default" @click="go">单击</button>
    </view>
</template>

<script>
export default {
    methods: {
        go() {
            uni.navigateTo({
                //普通跳转,可以返回当前页面
                url: '../detail/detail'
            })
        },
    }
}
</script>

(3)无历史记录,不能返回当前页面,使用 uni.redirectTo 方法,代码如下。

export default {
    methods: {
        go() {
            uni.redirectTo({
                //清除历史记录
                url: '../detail/detail'
            })
        },
    }
}

传递参数

页面跳转的同时传递参数,例如页面跳转传入 id 参数,代码如下。

export default {
    methods: {
        go() {
            uni.navigateTo({
                url: '../detail/detail?id=10'
            })
        },
    }
}

打开 detail.vue 页面,要获取 index.vue 传递的参数。前面讲过,onLoad 生命周期函数有两个作用,第一个作用是调用数据接口,第二个作用是获取上一个页面传递的参数,所以获取参数是在 onLoad 生命周期函数中实现的。

给 onLoad 传入形参,接收的参数就在形参中,代码如下。

<template>
    <view>
        商品详情
    </view>
</template>

<script>
export default {
    data() {
        return {

        }
    },
    onLoad(op){
        console.log(op)
    },
    methods: {

    }
}
</script>

控制台的打印结果如图 13-11 所示。

image 2025 02 12 15 51 01 719
Figure 1. 图13-11 获取传递参数

通过打印结果发现,op 是一个对象,id 就是传递的参数,要获取参数直接使用 console.log(op.id) 即可。