概要
Vue2.4.4及びOnsenUIのVue2向けモジュールであるvue-onsenui2.2.1を用いて、タブによる画面の切り替えの実装に関する備忘録。本記事では、以下のようにタブを切り替えることで描画するVueコンポーネントを切り替える。
※ 撮影の都合でgifがカクついてますが、実際はもっとヌルヌル切り替わります
前提
以下の環境で動作確認済み
debian | 9.2 |
vue | 2.4.4 |
vue-onsenui | 2.2.1 |
各タブに表示するコンポーネントを実装
本記事では、gifの通り「コンポーネント1」「コンポーネント2」「コンポーネント3」の3種類のコンポーネントをタブで切り替える。
まずは、その3種類のコンポーネントを作成する。といってもテキストを描画するだけの適当なもの。
component1.vue
<template> <v-ons-page> コンポーネント1 </v-ons-page> </template>
component2.vue
<template> <v-ons-page> コンポーネント2 </v-ons-page> </template>
component3.vue
<template> <v-ons-page> コンポーネント3 </v-ons-page> </template>
タブの実装
v-ons-tabbarを用いてタブを描画する
<template> <v-ons-page> <v-ons-tabbar position="auto" :visible="true" :tabs="tabs" :index.sync="tabIndex"> </v-ons-tabbar> </v-ons-page> </template>
上記templateに対して、tabIndexとtabsを定義する。tabsでは、各タブに表示するアイコンと、表示用ラベル、そしてタブがアクティブになった時に描画するコンポーネントを定義する。各タブに対して、前項で作成したコンポーネントをimportして適用する。
import component1 from './component1' import component2 from './component2' import component3 from './component3' export default { name: 'index', data() { return { tabIndex: 0, tabs: [ { icon: 'fa-home', label: '1', page: component1, }, { icon: 'fa-user', label: '2', page: component2, }, { icon: 'fa-cog', label: '3', page: component3, } ] } }, methods: { }, components: { component1, component2, component3 }, }