feat: example04 작성 완료

This commit is contained in:
junilHwang
2020-10-25 21:02:15 +09:00
parent f11dca9121
commit a78e9c25cb
5 changed files with 83 additions and 5 deletions

11
example04/index.html Normal file
View 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
View File

@@ -0,0 +1,10 @@
import Items from "./components/Items.js";
class App {
constructor() {
const $app = document.querySelector('#app');
new Items($app);
}
}
new App();

View 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 });
}))
}
}

View 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();
}
}