由于web端和app公用一套菜单,而两个项目的路径是不同的,为解决这个问题,封装了一套使用路由名称作为跳转路由的方法

1.在pages.json文件里pages对应的页面配置里添加 routeName 字段(自定义),我做的app里面的菜单是后台获取的,所以这里的value值对应的是后台返回的页面路由

 

2.开始封装函数

创建route文件夹,在里面创建index.js和router.js

(1).router.js是为了获取page.json里面的路由,里面内容如下:

const defaultPages = require('@/pages.json')
const {
    pages,
} = defaultPages.default

function getRouters() {
    const _routes = {}
    pages.forEach(item => {
        _routes[item.routeName] = `/${item.path}`
    })
    
    return _routes
}

export default getRouters()

(2).在index.js文件里引入router.js,拿到路由集合实现跳转,index.js里面的代码如下:

import routers from './router';

/**
 * 路由跳转
 * @param name 页面路由名称
 * @param type 跳转方式
 * @param params 携带参数
 * @param delta 页面返回层级,仅 type='navigateBack' || type='back' 时生效
 */
function customRoute(config) {
    let _routeName = typeof config === 'string' ? config : config.name
    let _params = typeof config === 'string' ? {} : config.params || {}
    let _type = typeof config === 'string' ? 'navigateTo' : config.type || 'navigateTo'
    let _url = routers[_routeName]

    if (_type === 'navigateTo' || _type === 'to') {
        uni.navigateTo({ url: _url })
    }
    if (_type === 'redirectTo' || _type === 'redirect') {
        uni.redirectTo({ url: _url })
    }
    if (_type === 'switchTab' || _type === 'tab') {
        uni.switchTab({ url: _url })
    }
    if (_type === 'reLaunch' || _type === 'launch') {
        uni.reLaunch({ url: _url })
    }
    if (_type === 'navigateBack' || _type === 'back') {
        uni.navigateBack({ delta: _params.delta || 1 })
    }
}

export default customRoute

3.在main.js里面挂载到Vue实例

import customRoute from '@/route'
Vue.prototype.$routeTo = customRoute

跳转方式:我这里是获取到的地址

this.$routeTo(item.url)