LoginSignup
11
7

More than 3 years have passed since last update.

コンパイルなしでvueコンポーネントを外部ファイル化

Posted at

webpackなどのコンパイルツールを利用せずにvueを利用して、
コンポーネントを外部ファイル化してみた。

単一ファイルコンポーネント(.vue)なら、
タグを利用するところを.jsでテンプレートリテラルを利用します。

home_component.js
const template = `
<div>
    {{ message }}
</div>
`;

export default {
    template,
    data() {
        return {
            message : "home page"
        }
    }
}
child_component.js
const template = `
<div>
    {{ message }}
</div>
`;

export default {
    template,
    data() {
        return {
            message : "child page"
        }
    }
}

インポートする側では普通にimportして、利用します。

import.js
import HomeComponent from './home_component.js';
import ChildComponent from './child_component.js';


const router = new VueRouter({
    mode: "history",
    routes:[
        { name:'home',path: '/', component: HomeComponent },
        { name:'child',path: '/child', component: ChildComponent },
    ]
});

const app = new Vue({
    router
}).$mount('#app');

htmlでは、cdnでvue, vue-routerを読み込みます。

index.html
<html>
<head>
    <style type="text/css">
        [v-cloak] {
            display: none;
        }
    </style>
</head>
<div id="app" v-cloak>
    <router-link to="/">home</router-link>
    <router-link to="/child">child</router-link>
    <router-view></router-view>
</div>
<script src="https://cdn.jsdelivr.net/npm/vue@2.5.21/dist/vue.js"></script>
<script src="https://unpkg.com/vue-router/dist/vue-router.js"></script>
<script src="import.js" type="module"></script>
</html>

スクリーンショット 2019-09-01 22.19.36.png
スクリーンショット 2019-09-01 22.21.37.png

11
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
11
7