feat: example04 작성 완료
This commit is contained in:
@@ -21,3 +21,4 @@ export default class Items extends Component {
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
11
example04/index.html
Normal file
11
example04/index.html
Normal file
@@ -0,0 +1,11 @@
|
||||
<!doctype html>
|
||||
<html lang="ko">
|
||||
<head>
|
||||
<meta charset="UTF-8">
|
||||
<title>Simple Component 2</title>
|
||||
</head>
|
||||
<body>
|
||||
<div id="app"></div>
|
||||
<script src="./src/app.js" type="module"></script>
|
||||
</body>
|
||||
</html>
|
||||
10
example04/src/app.js
Normal file
10
example04/src/app.js
Normal file
@@ -0,0 +1,10 @@
|
||||
import Items from "./components/Items.js";
|
||||
|
||||
class App {
|
||||
constructor() {
|
||||
const $app = document.querySelector('#app');
|
||||
new Items($app);
|
||||
}
|
||||
}
|
||||
|
||||
new App();
|
||||
36
example04/src/components/Items.js
Normal file
36
example04/src/components/Items.js
Normal file
@@ -0,0 +1,36 @@
|
||||
import Component from "../core/Component.js";
|
||||
|
||||
export default class Items extends Component {
|
||||
setup () {
|
||||
this.$state = { items: ['item1', 'item2'] };
|
||||
}
|
||||
template () {
|
||||
const { items } = this.$state;
|
||||
return `
|
||||
<ul>
|
||||
${items.map((item, key) => `
|
||||
<li>
|
||||
${item}
|
||||
<button class="deleteBtn" data-index="${key}">삭제</button>
|
||||
</li>
|
||||
`).join('')}
|
||||
</ul>
|
||||
<button class="addBtn">추가</button>
|
||||
`
|
||||
}
|
||||
|
||||
setEvent () {
|
||||
this.$target.querySelector('.addBtn').addEventListener('click', () => {
|
||||
const { items } = this.$state;
|
||||
this.setState({ items: [ ...items, `item${items.length + 1}` ] });
|
||||
});
|
||||
|
||||
this.$target.querySelectorAll('.deleteBtn').forEach(deleteBtn =>
|
||||
deleteBtn.addEventListener('click', ({ target }) => {
|
||||
const items = [ ...this.$state.items ];
|
||||
items.splice(target.dataset.index, 1);
|
||||
this.setState({ items });
|
||||
}))
|
||||
}
|
||||
}
|
||||
|
||||
20
example04/src/core/Component.js
Normal file
20
example04/src/core/Component.js
Normal file
@@ -0,0 +1,20 @@
|
||||
export default class Component {
|
||||
$target;
|
||||
$state;
|
||||
constructor ($target) {
|
||||
this.$target = $target;
|
||||
this.setup();
|
||||
this.render();
|
||||
}
|
||||
setup () {};
|
||||
template () { return ''; }
|
||||
render () {
|
||||
this.$target.innerHTML = this.template();
|
||||
this.setEvent();
|
||||
}
|
||||
setEvent () {}
|
||||
setState (newState) {
|
||||
this.$state = { ...this.$state, ...newState };
|
||||
this.render();
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user