6
7

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

vue-routerでのレイアウトの出し分け

Last updated at Posted at 2019-07-01

したいこと

ログイン画面とその他の画面で表示するレイアウトを変えたい

環境

laravel vue.js
5.8.26 2.9.6

実装

index.blade.php
<body>
    <div id="app">
        <app></app>
    </div>
    <script src="{{ mix('js/app.js') }}"></script>
</body>

resources/js/router.js
import VueRouter from 'vue-router';

import Login from './components/Login.vue'
import Top from './components/Top.vue'

const router = new VueRouter({
    mode: 'history',
    base: '/',
    routes: [{
            path: '/login',
            name: 'login',
            // metaにlayoutを追加
            meta: { layout: 'none'},
            component: Login
        },
        {
            path: '/',
            name: 'top',
            component: Top
        }
    ]
});

export default router;

  • デフォルトレイアウトのcomponent作成
  • ヘッダーフッターのないログイン用レイアウトのcomponent作成
resources/js/components/layout/DefaultLayout.vue
<template>
    <div>
        <custom-header/>
        <router-view></router-view>
        <custom-footer/>
    </div>  
</template>
<script>
// ヘッダー、フッターコンポーネントをimport
// コンポーネントの詳細は省略
import CustomHeader from '../common/Header'
import CustomFooter from '../common/Footer'

export default {
    name: 'login',
    components: {
        CustomHeader,
        CustomFooter,
    },
}
</script>
resources/js/components/layout/NoneLayout.vue
<template>
    <div>
        <router-view></router-view>
    </div>  
</template>

resources/js/components/App.vue
<template>
    <div>
     <!-- v-bind:isでタブインタフェースのコンポーネントを切り替えられる -->
        <component v-bind:is="layout()"></component>
    </div>
</template>

<script>
// レイアウトコンポーネントをインポート
import DefaultLayout from './layout/DefaultLayout.vue';
import NoneLayout from './layout/NoneLayout.vue';

export default {
    components: {
        DefaultLayout,
        NoneLayout
    },
    methods: {
        layout() {
            // router.jsのroutesにmeta.layoutの存在確認
            // セットするレイアウトを判断する
            let layout = this.$route.meta.layout ? this.$route.meta.layout + '-layout' : 'default-layout';
            return layout;
        }
    }
}
</script>
6
7
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
6
7

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?