LoginSignup
5
7

More than 5 years have passed since last update.

vueでwebpackを使わないけど、ファイルの分割はやりたいという人向け

Last updated at Posted at 2018-11-14

内容はタイトルどおり。

環境を特に準備することなく、さらっと書きたいとか。
ちょこっとだけ書きたいけど、vue.componentは使いたいとか。。。
なにが嬉しいかは人それぞれなので。

簡単なんで、前振りはここまでで実物の全容を見ればよいかと。

Vue Componentでファイル分割

サンプル
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body>

<div id="components-demo">
    <hello-world></hello-world>
    <hello-world2></hello-world2>
</div>


<script src="https://unpkg.com/vue"></script>
<script src="addComponent.js"></script>
<script>

    addComponent({
        name: "hello-world",
        url: "./vuetest_template.html",
        props: [],
    });
    addComponent({
        name: "hello-world2",
        url: "./vuetest_template2.html",
        props: [],
    });

    new Vue({el: '#components-demo'});

    }

</script>
</body>
</html>
vuetest_template.html
<div>
    test
</div>
vuetest_template2.html
<div>
    test2
</div>

こんな感じです。特に難しいことない。
addComponentは、今回特別に作った所。
嬉しい(?)ことに、個々に分割されたファイルの内容は必要な時のみ読み込みが発生する。

で、addComponentの実装がこちら。
(細かなjsのテクニックは自分で追記してください)

addComponent.js
function addComponent(p) {
    Vue.component(p.name, function (resolve, reject) {
        fetch(p.url)
            .then((response) => {
                if (response.ok) {
                    return response.text();
                } else {
                    resolve({template: "<p>template not found</p>"});
                    throw new Error();
                }
            })
            .then((text) => resolve({template: text, props: p.props, data: p.data}))
            .catch((error) => {
            });
    });
}

マニュアルでは、こんな感じで書いてある
https://jp.vuejs.org/v2/guide/components-dynamic-async.html

Vue router でファイル分離

テンプレートを非同期でセットしても良い。

const Bar = {template: ''};
fetch("bar.html")
    .then(res => res.text())
    .then(text => {
        Bar.template = text
    })
    .catch(err => {
        alert(err)
    });
const router = new VueRouter({
    routes: [
       {path: '/bar', component: Bar}
    ],
});
const app = new Vue({
    el: '#app',
    router,
    data: {},
});

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