前端组知识库

👍欢迎大家积极投稿交流👍

如果文档内容陈旧或者链接失效,请发现后及时同步,我将尽快修改

👇微信👇

图片
Skip to content

路由配置

项目中已集成 @uni-helper/vite-plugin-uni-pages插件,所有新增的文件,都会自动配置在pages.json文件中,不需要手动配置,也解决了多人开发出现的冲突问题。

vite-plugin-uni-pages 官方文档

定义页面

对象形式

pages/index/index.vue
vue
<script setup lang="ts">
definePage({
  style: {
    navigationBarTitleText: '首页',
  },
})
</script>

函数形式

pages/index/index.vue
vue
<script setup lang="ts">
definePage(() => {
  const words = {
    hello: 'hello',
    world: 'world',
  }

  return {
    style: {
      navigationBarTitleText: [words.hello, words.world].join(' '),
    },
  }
})
</script>

嵌套函数

pages/index/index.vue
vue
<script setup lang="ts">
definePage(() => {
  function getTitle(): string {
    const hello = 'hello'
    const world = 'world'

    return [hello, world].join(' ')
  }

  return {
    style: {
      navigationBarTitleText: getTitle(),
    },
  }
})
</script>

异步数据获取

pages/index/index.vue
vue
<script setup lang="ts">
definePage(async () => {
  const words = await getWords()

  return {
    style: {
      navigationBarTitleText: words,
    },
  }
})
</script>

条件编译

框架默认已安装@uni-helper/uni-env插件

sh
npm i @uni-helper/uni-env
sh
pnpm i @uni-helper/uni-env
sh
bun add @uni-helper/uni-env
sh
yarn add @uni-helper/uni-env
pages/index/index.vue
vue
<script setup lang="ts">
import { isH5 } from '@uni-helper/uni-env'

definePage(() => {
  let title = ''

  title = isH5 ? 'H5 环境' : '非 H5 环境'

  // OR uniapp 条件编译

  // #ifdef H5
  title = 'H5 环境'
  // #endif
  // #ifndef H5
  title = '非 H5 环境'
  // #endif

  return {
    style: {
      navigationBarTitleText: title,
    },
  }
})
</script>

路由跳转

不继承三方插件,原汁原味,通过路由拦截的方案实现基础功能,框架中默认启用了路由拦截,文件配置在src/router/interceptor.ts,并封装了以下功能:

  1. 跳转路径不存在,默认进入/subpackages/auth/404/index页面
  2. 跳转路径是当前路径,拦截不跳转
  3. 跳转页面支持对象方式传递页面参数
  4. 返回拦截,如果返回层级大于当前层级,默认返回首页

跳转示例

typescript
// 跳转页面
uni.navigateTo({
  url: '/pages/detail/index',
})

// 跳转页面,携带参数
uni.navigateTo({
  url: '/pages/detail/index',
  query: {
    id: 1,
  },
})

// 关闭当前页面,跳转到应用内的某个页面。
uni.redirectTo({
  url: '/pages/detail/index',
  query: {
    id: 1,
  },
})

// 关闭所有页面,打开到应用内的某个页面。
uni.reLaunch({
  url: '/pages/index/index',
})

// 关闭所有页面,打开到应用内的某个页面,携带参数。
uni.reLaunch({
  url: '/pages/index/index',
  query: {
    id: 1,
  },
})

// 跳转到 tabBar 页面,并关闭其他所有非 tabBar 页面,不支持携带参数。
uni.switchTab({
  url: '/pages/index/index',
})

// 关闭当前页面,返回上一页面或多级页面,不支持携带参数,delta 指定返回的层级,不传默认为1。
uni.navigateBack()

uni.navigateBack({
  delta: 2,
})

// 返回层级大于当前层级,默认返回首页
uni.navigateBack({
  delta: 20,
})