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>

