【小程序】使用uni-app搭建小程序环境---路由配置及页面跳转获取参数

路由

uni-app路由全部交给框架统一管理,开发者需要在pages.json里配置每个路由页面的路径及页面样式,不支持 Vue Router

范例:

  

    "pages": [ //pages数组中第一项表示应用启动页,参考:https://uniapp.dcloud.io/collocation/pages
        {
            "path": "pages/index/index",
            "style": {
                "navigationBarTitleText": "首页"
            }
        },
        {
            "path": "pages/courseCassify/index",
            "style": {
                "navigationBarTitleText": "分类"
            }
        },
        {
            "path": "pages/learnRecord/index",
            "style": {
                "navigationBarTitleText": "学习"
            }
        },
        {
            "path": "pages/my/index",
            "style": {
                "navigationBarTitleText": "我的"
            }
        }
    ],

路由跳转

uni-app 有两种路由跳转方式:使用navigator组件跳转、调用API跳转。

<template>
    <view>
        <view class="page-body">
            <view class="btn-area">
                <navigator url="navigate/navigate?title=navigate" hover-class="navigator-hover">
                    <button type="default">跳转到新页面</button>
                </navigator>
                <navigator url="redirect/redirect?title=redirect" open-type="redirect" hover-class="other-navigator-hover">
                    <button type="default">在当前页打开</button>
                </navigator>
                <navigator url="/pages/tabBar/extUI/extUI" open-type="switchTab" hover-class="other-navigator-hover">
                    <button type="default">跳转tab页面</button>
                </navigator>
            </view>
        </view>
    </view>
</template>
// navigate.vue页面接受参数
export default {
    onLoad: function (option) { //option为object类型,会序列化上个页面传递的参数
        console.log(option.id); //打印出上个页面传递的参数。
        console.log(option.name); //打印出上个页面传递的参数。
    }
}

url有长度限制,太长的字符串会传递失败,可使用窗体通信全局变量,或encodeURIComponent等多种方式解决,如下为encodeURIComponent示例。

<navigator :url="'/pages/navigate/navigate?item='+ encodeURIComponent(JSON.stringify(item))"></navigator>



// navigate.vue页面接受参数
onLoad: function (option) {
    const item = JSON.parse(decodeURIComponent(option.item));
}

注意

  • 跳转tabbar页面,必须设置open-type="switchTab"