导航路由
Framework7 Svelte 本身就包含强大的灵活路由器。为了让它工作,我们必须指定 路由。
Framework7 Svelte 的唯一区别是,在 Svelte 中我们已经用 Svelte 组件来构建应用程序,所以我们需要将我们的页面(Svelte 组件)映射到路由。这可以通过在路由的 component
属性中传递 Svelte 组件来实现。以下是一个基本示例
<!-- App.svelte -->
<App { ...f7params }>
<!-- Current View/Router, initial page will be loaded from home.svelte component -->
<View main url="/" />
</App>
<script>
// Import pages components
import HomePage from 'home.svelte';
import AboutPage from 'about.svelte';
import LoginPage from 'login.svelte';
/*
Now we need to map components to routes.
We need to pass them along with the F7 app parameters to <App> component
*/
const f7params = {
name: 'My App',
// specify routes for app
routes: [
{
path: '/',
component: HomePage,
},
{
path: '/about/',
component: AboutPage,
},
{
path: '/login/',
component: LoginPage,
},
],
};
</script>
<!-- home.svelte -->
<Page name="home">
<Navbar title="Home Page" />
...
<Link href="/about/">About Page</Link>
<Link href="/login/">Login Page</Link>
</Page>
<script>
import { Page, Navbar, Link } from 'framework7-svelte';
</script>
<!-- about.svelte -->
<Page name="about">
<Navbar title="About" />
<!-- Page content -->
...
</Page>
<script>
import { Page, Navbar } from 'framework7-svelte';
</script>
<!-- login.svelte -->
<Page name="login">
<Navbar title="Login" />
<!-- Page content -->
...
</Page>
<script>
import { Page, Navbar } from 'framework7-svelte';
</script>
传递属性到组件
可以将组件属性传递到由路由器加载的 Svelte 组件。有几种方法可以做到这一点。
首先,所有路由参数都会自动作为属性传递给组件,例如:
// route with params
{
path: '/blog/:postId/comments/:commentId/',
component: BlogPost,
}
因此,如果我们通过 /blog/45/comments/122/
URL 导航,那么以下数据将被传递给属性
{
postId: '45',
commentId: '122',
}
另一个选择是在路由的 options
中指定属性
{
path: '/some-page/',
component: SomeComponent,
options: {
props: {
foo: 'bar',
bar: true,
},
},
}
最后,当我们使用 API 导航时,可以动态地将属性传递给路由组件
f7router.navigate('/some-page/', {
props: {
foo: 'bar',
bar: true,
}
})
异步延迟组件
使用 Webpack 可以按需加载页面组件,这可以通过 F7 的路由 asyncComponent
来实现,例如
{
path: '/about/',
asyncComponent: () => import('./pages/about.svelte'),
},
或者,如果我们需要更多控制,可以使用 async
路由
{
path: '/about/',
async({ resolve }) {
// dynamic import component, returns promise
import('./pages/about.svelte').then((module) => {
// resolve with component
resolve({ component: module.default })
});
} ,
},
路由器 API
要访问路由器实例并使用 路由器 API,可以使用组件的特殊 f7router 组件属性
<Page>
...
<Link onClick={() => f7router.navigate('/about/')}>About</Link>
<Link onClick={() => f7router.back()}>Go Back</Link>
</Page>
<script>
import { onMount } from 'svelte';
import { Page, Link } from 'framework7-svelte';
// Router component will receive f7router prop with current Router instance
export let f7router;
// Router component will receive f7route prop with current route data
export let f7route;
onMount(() => {
// output current route data
console.log(f7route); // -> { url: '/foo/', query: { id: 3 }, ... }
});
</script>