uniapp是一款基于vue.js的跨平台应用开发框架,通过统一的语法规范和封装的api,支持快速构建小程序、h5、app等多平台应用,同时提供了丰富的路由和页面跳转api来实现应用之间的跳转和页面之间的交互。
下面我们来详细介绍Uniapp常见的路由与页面跳转API:
路由
路由是指应用之间的跳转规则,Uniapp提供了多种路由的配置方式,包括全局路由配置、页面独享配置、组件路由配置等,通过路由可以实现应用之间的快速跳转和页面之间的参数传递。
全局的路由配置包含了应用的所有路由规则,在main.js文件中进行配置,具体方法如下:
import App from './App'
// 全局路由配置
const router = uni.createRouter({
routes: [
{
path: '/home',
name: 'home',
component: () => import('@/pages/home/index.vue')
},
{
path: '/category',
name: 'category',
component: () => import('@/pages/category/index.vue')
},
{
path: '/goods/:id',
name: 'goods',
component: () => import('@/pages/goods/index.vue')
},
//...
]
})
App.mpType = 'app'
App.router = router
App.vue = new Vue({
router,
render: h => h(App)
}).$mount()在全局路由配置中,可以定义多个路由规则,每个路由规则包含了path、name和component三个属性。其中,path表示路由的路径,name表示路由的名称,component表示路由对应的组件。
在Uniapp中,路由的跳转可以通过uni.navigateTo、uni.switchTab、uni.reLaunch等API来实现,接下来我们将详细介绍这些API的用法。
页面独享的路由配置可以针对特定页面进行路由规则的定义,将路由规则写在页面的配置中,具体方法如下:
<template>
<view class="container">
<!-- ... -->
</view>
</template>
<script>
export default {
name: 'home',
// 页面独享配置
onUniNaviationBarTap(){
uni.navigateTo({
url:'/pages/category/index'
})
}
}
</script>
<style>
/* ... */
</style>在页面独享配置中,可以定义多个路由规则,以事件的形式触发,这些事件包括onLoad、onShow、onUnload、onHide等。
组件路由配置可以实现组件之间的路由跳转,将路由规则写在组件中,具体方法如下:
<template>
<view class="container" @click="goToGoodsDetail">
<!-- ... -->
</view>
</template>
<script>
export default {
name: 'product-card',
methods: {
goToGoodsDetail() {
uni.navigateTo({
url: '/pages/goods/index?id=' + this.goodsId
})
},
},
props: {
goodsId: {
type: String,
required: true,
},
},
}
</script>
<style>
/* ... */
</style>通过在组件中定义路由规则,并触发uni.navigateTo,就可以实现组件之间的跳转。
页面跳转API
Uniapp提供了多种页面跳转的API,包括navigateTo、redirectTo、switchTab、reLaunch等,通过这些API,可以实现应用之间的快速跳转和页面之间的参数传递。
navigateTo是最常用的页面跳转API之一,用于在当前页面打开一个新页面,新页面可以通过uni.navigateBack返回到当前页面。
uni.navigateTo({
url: '/pages/category/index'
})在navigateTo中,url表示跳转的页面路径,可以是相对路径或绝对路径。
redirectTo用于关闭当前页面并打开一个新页面,新页面不可以通过uni.navigateBack返回到当前页面。
uni.redirectTo({
url: '/pages/category/index'
})switchTab用于打开应用的Tab页面,页面无法传递参数,可以在Tab页面通过onLoad实现初始化操作。
uni.switchTab({
url: '/pages/home/index'
})reLaunch用于关闭所有页面并打开一个新页面,新页面可以通过uni.navigateBack返回到当前页面。
uni.reLaunch({
url: '/pages/login/index'
})总结
本文详细介绍了Uniapp常见的路由与页面跳转API,在应用开发中,路由与页面跳转是非常重要的一环,通过灵活的配置和使用这些API,可以实现应用之间的跳转和页面之间的交互,为用户带来更好的体验和更优质的服务。
以上就是uniapp常见的路由与页面跳转api是什么的详细内容,更多请关注php中文网其它相关文章!
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号