npm i miniapp-router -S
//page.js import demodata from './data'; import routerConfig from './router'; //路由定义 import routerInit from 'miniapp-router'; //引入初始化方法 Page({ data: { demodata, typeName: 'Component 组件', componentName: 'Button 按钮', type: 'component', component: 'button', selectedKeys: ['button, input'], }, onLoad() { routerInit.call(this, routerConfig); //注意需要传入this,会绑定$router至页面this上,子组件可通过this.$page获取页面this }, onItemClick(event) { let { typeName, componentName, type, component } = event.target.dataset; this.setData({ typeName, componentName, type, component }); this.$router.push(`/${type}/${component}`); }, });
export default { routes: [ { path: '/component', component: 'component', children: [ { path: '/button', component: 'button' }, { path: '/icon', component: 'icon' }, { path: '/menu-button', component: 'menu-button' }, { path: '/select', component: 'select' }, { path: '/slider', component: 'slider' }, { path: '/menu', component: 'menu' }, { path: '/progress', component: 'progress' }, { path: '/input', component: 'input' }, { path: '/textarea', component: 'textarea' }, { path: '/switch', component: 'switch' }, { path: '/radio', component: 'radio' }, { path: '/checkbox', component: 'checkbox' }, { path: '/date-picker', component: 'date-picker' }, { path: '/pagination', component: 'pagination' }, { path: '/table', component: 'table' }, ], }, { path: '/scene', component: 'scene', children: [{ path: '/form', component: 'form' }], }, { path: '/api', component: 'api', children: [ { path: '/other', component: 'other' }, { path: '/media', component: 'media' }, { path: '/interface', component: 'interface' }, { path: '/network', component: 'network' }, { path: '/base', component: 'base' }, ], }, ], option: { initPath: '/component/button', }, };
注意slot需和路由定义中的component对应。
//page.axml <view class="body-content"> <router-view> <base slot="component" /> <scene slot="scene" /> <api slot="api" /> </router-view> </view>
//components/base.axml <view> <view class="content-main-container" /> <router-view> <button slot="button" /> <slider slot="slider" /> <icon slot="icon" /> <text slot="text" /> <progress slot="progress" /> <menu slot="menu" /> <select slot="select" /> <textarea slot="textarea" /> <input slot="input" /> <checkbox slot="checkbox" /> <switch slot="switch" /> <radio slot="radio" /> <pagination slot="pagination" /> <date-picker slot="date-picker" /> <menu-button slot="menu-button" /> <table slot="table" /> </router-view> </view> </view>