导航路由
Framework7-Vue 与 Framework7 本身一样,都带有强大灵活的路由器。为了使之运行,我们必须指定路由。
Framework7-Vue 中唯一的区别在于在 Vue.js 中,我们已经用 Vue 组件来构建我们的应用程序,所以我们需要将我们的页面(Vue 组件)映射到路由。这可以通过在路由的 component
属性中传入 Vue 组件来完成。以下是一个基本示例
<!-- app.vue -->
<template>
<f7-app v-bind="f7params">
<!-- Current View/Router, initial page will be loaded from home.vue component -->
<f7-view main url="/"></f7-view>
</f7-app>
</template>
<script>
/* Import pages components */
import HomePage from 'home.vue'
import AboutPage from 'about.vue'
import LoginPage from 'login.vue'
/*
Now we need to map components to routes.
We need to pass them along with the F7 app parameters to <f7-app> component
*/
export default {
data() {
return {
// app params
f7params: {
name: 'My App',
// specify routes for app
routes: [
{
path: '/',
component: HomePage,
},
{
path: '/about/',
component: AboutPage,
},
{
path: '/login/',
component: LoginPage,
},
// ...
],
// ...
}
};
},
}
</script>
<!-- home.vue -->
<template>
<f7-page name="home">
<f7-navbar title="Home"></f7-navbar>
<!-- Page content -->
...
<f7-link href="/about/">About Page</f7-link>
<f7-link href="/login/">Login Page</f7-link>
</f7-page>
</template>
<script>
export default {}
</script>
<!-- about.vue -->
<template>
<f7-page name="about">
<f7-navbar title="About"></f7-navbar>
<!-- Page content -->
</f7-page>
</template>
<script>
export default {}
</script>
<!-- login.vue -->
<template>
<f7-page name="login">
<f7-navbar title="Login"></f7-navbar>
<!-- Page content -->
</f7-page>
</template>
<script>
export default {}
</script>
将属性传递给组件
可以将组件属性传递给由路由加载的 Vue 组件。有几种方法可以做到这一点。
首先,所有路由参数都将自动作为属性传递给组件,例如
// 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.vue'),
},
或者使用 async
路由,如果我们需要对它有更多的控制
{
path: '/about/',
async({ resolve }) {
// dynamic import component; returns promise
const vueComponent = () => import('./pages/about.vue');
// resolve promise
vueComponent().then((vc) => {
// resolve with component
resolve({ component: vc.default })
});
} ,
},
路由 API
要访问路由实例并使用路由 API,可以使用组件的特殊 f7router 组件属性
<template>
...
<f7-link @click="f7router.navigate('/about/')">About</f7-link>
<f7-link @click="f7router.back()">Go Back</f7-link>
</template>
<script>
export default {
props: {
f7router: Object,
}
}
</script>
请注意,f7route
和 f7router
组件属性仅在根据路由加载的自定义页面组件中可用。它们在父组件(如在 View 中,或初始化 Vue 应用实例的地方)和子组件中不可访问。因此在这种情况下可以使用访问已初始化的 View 实例,例如 f7.views.main.router