5
2

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.

Laravel+vueでnuxtのlayoutComponentっぽいことがしたい

5
Last updated at Posted at 2019-12-15

正解がわからないので、いい方法教えてほしいです。

正解はこちらでした
https://github.com/ktsn/vue-router-layout

LaravelはAPIオンリーでnuxtjsにしたいですが、諸事情ありで出来ないときできるだけvueだけで管理したく、Laravelのlayoutを使うと密結合だし、vueとLaravelのbladeを両方管理しないといけないので、分離したいです。
vueRouterでlayout設定するのが正義なのか??

component登録はフォルダまるごと

reesources/js/app.js

//|-- app.js
//|-- vue
//|-- |-- pages
//|-- |-- |-- Sample
//|-- |-- |-- |-- Index.vue

// 正規表現で.vueのついたファイルをまるごとrequire
const files = require.context('./vue/pages/', true, /\.vue$/i);
// そのfilesをmapで回して、コンポーネント登録
files.keys().map(key => {
    const split = key.split('/');
    Vue.component(
        split.reverse()[1] + split.pop().split('.')[0],
        files(key).default
    );
// 例: 
// Vue.component(
//    'SampleIndex', 
//    require('./vue/pages/Sample/Index.vue').default
// );
});

Laravelのブレードはシンプルに

上記でvueにComponent登録は終わってるものとして、SampleIndexを呼び出す

sample.blade.php
<!DOCTYPE html>
<html>
<head>
  @include('layouts.header')
</head>
<body>
  <div id="app">
    <sample-index />
  </div>
</body>
</html>

Vueのページコンポーネントとして

本来ならexport default { layout: 'default' }にしたいけどやり方がわからなくて、<Layout>を呼び出す。ここで変更したいときは<Layout name="default">のようにname属性で変更する。

pages/SampleContent.vue
<template>
  <Layout>
    SampleIndex
  </Layout>
</template>

<script>
import Layout from '@/layouts/Layout';
export default {
  components: {
    Layout
  }
}
</script>
layouts/Layout.vue
<template>
  <component :is="name">
    <slot />
  </component>
</template>

<script>
export default {
  props: {
    name: {
      type: String,
      default: 'Default'
    }
  }
}
</script>
layouts/Default.vue
<template>
  <div class="default">
    <header />
    <main>
      <slot />
    </main>
    <footer />
  </div>
</template>

5
2
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
5
2

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?