- vuejs의 분리된 컴포넌트 파일(*.vue)을 자바스크립트 모듈 파일(*.js, *.mjs)로 만들어 esm(es6 module)로 활용하기
- webpack없이 vue 컴포넌트를 분리해서 사용하는 방법


https://vuejsdevelopers.com/2017/09/24/vue-js-single-file-javascript-components/

//====================================
// vc_js.htm

<!DOCTYPE html>
<html>

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

<body>
    <div id="app">
        <vc-obj1></vc-obj1>
        <vc-obj2></vc-obj2>

    </div>
    <script type="module" src="./vc_js_app.js"></script>
</body>

</html>
<script>
    //impoert 된 모든 개체를 하나의 개체로 만듬
    function getImportedObj(imported) {
        let comps = {}
        Object.entries(imported).forEach(
            ([name, val]) => {
                //window[name] = val
                //console.log(name, val);
                if (name === 'default') {
                    Object.assign(comps, getImportedObj(val));
                } else {
                    comps[name] = imported[name];
                }
            }
        );
        return comps;
    }
</script>


//===================================================
// vc_js_app.js

//import vc_js from './vc_js.js';
import * as vc_js from './vc_js.js';

new Vue({
    el: '#app',
    //components: {    vcObj1: vc_js.vcObj1,  }
    components: getImportedObj(vc_js),
});



//============================
// vc_js.js

export default {
    /* 
    //1개만 내보낼때
    template: `<div><p>{{ message }}</p></div>`,
    data() {
      return {
        message: 'component - 0'
      }
    } */

    //여러개 내보낼 경우
    vcObj1: {
        template: `<div><p>{{ message }}</p></div>`,
        data() {
            return {
                message: 'component - 1'
            }
        }
    }
}

//
var vcObj2 = {
    template: `<div><p>{{ message }}</p></div>`,
    data() {
        return {
            message: 'component - 2'
        }
    }
}

export {
    vcObj2
}

 

Posted by 코덴스

댓글을 달아 주세요