- 본 글은 Svelte에서 Component 정의 및 사용법에 대해 기술하겠습니다.
- React, Vue와 차이점을 중심으로 기술하겠습니다.
컴포넌트 정의 및 사용.
기존의 library or framework와 같이 jsx, vue와 같이 .svelte extensions를 가진 파일에 컴포넌트를 정의 후 export 합니다.
필요한 컴포넌트를 import 후 사용 및 props를 전달합니다.
React와 사용 방법이 흡사합니다. Component를 import 후 원하는 위치에 component를 사용하면 됩니다.
Vue의 경우 Vue instance 내부에 component를 등록 후 사용해 주어야 합니다.
//React//Index.jsximportReactfrom'react'importItemfrom"./Item";exportdefaultfunctionIndex(){const[name]=React.useState('React');const[inputValue,setInputValue]=React.useState("");const[list,setList]=React.useState(['item1','item2']);constinputRef=React.useRef(null);constonClick=()=>{constvalue=inputRef?.current?.value;setList(prevState=>[...prevState,value]);}return(<main><h1style=>Hello {name}</h1><p>Visit the {name}</p><inputref={inputRef}type="text"placeholder="입력"value={inputValue}onChange={(e)=>setInputValue(e.target.value)}/><buttononClick={onClick}>입력</button><div>입력 값 : {inputValue}</div>{list?.length&&list.map((item)=><Itemtext={item}/>)}</main>)}// Item.jsximportReactfrom'react'exportdefaultfunctionItem({text}){return(<li>{text}</li>)}
//Index.vue
<script>//Vue//Index.vueimportItemfrom"./Item";exportdefault{components:{Item},data:function(){return{name:'Vue',inputValue:'',list:['item1','item2']}},methods:{onClick(){this.list.push(this.inputValue);}}}</script><template><main><h1>Hello </h1><!-- <p@click="()=>console.log('click Vue')">Visit the !!.</p> Vue instance 외부 global에 접근할 수 없음.-->
<p>Visit the !!.</p><inputtype="text"placeholder="입력"v-model="inputValue"><buttonv-on:click="onClick">입력</button><div>입력 값 : </div><Itemv-for="text in list"v-bind:text="text"/></main></template><style>main{text-align:center;padding:1em;max-width:240px;margin:0auto;}h1{color:#47C83E;text-transform:uppercase;font-size:4em;font-weight:100;}input{margin-bottom:10px;margin-top:20px;}@media(min-width:640px){main{max-width:none;}}</style>
// Item.vue
<template><li></li></template><script>exportdefault{name:"Item.vue",props:['text']}</script>