-
23_11_22 JS공부정리개발공부/JavaScript 2023. 11. 23. 00:21
[코딩애플] Part3
-커스텀 태그
Web Components : JS문법으로 구현할 수 있는 브라우저 기본 기능<커스텀태그>의 장점
-html중복제거, 다른 페이지에서 재활용가능class 클래스 extends HTMLElement {connectedCallback() {this.innerHTML = `<label>이메일인풋이에요</label><input>`//만든 태그가 HTML에 장착될때 실행할 코드 적는곳}}
customElements.define('custom-input', 클래스); //첫번째 자리에는 만들 태그이름, 두번째에는 클래스
</script>
<custom-input></custom-input>*this는 여기서 새로 생성될 <custom-input>의 요소.
-this.innerHTML대신에 document.createElement();를 쓰는게 더 빠름
let element = document.createElement('label');this.appendChild(element) //이런식으로 쓰면 더 로딩속도가 더 빠름-함수의 파라미터처럼, Attribute를 활용하여 파라미터처럼 쓸 수 있음
<custom-input name="비번"></custom-input>class 클래스 extends HTMLElement {connectedCallback() {this.innerHTML = `<label>${name}인풋이에요</label><input>`let name = this.getAttribute('name')}}-태그의 Attribute가 바뀌는걸 감지해서 특정함수를 실행시킬 수도 있음.
-static get observedAttributes() {return[속성]} : 속성이 변경되는 것을 감지
-attributeChangedCallback() {함수} : 속성이 변경되면 함수 실행.
class 클래스 extends HTMLElement {connectedCallback() {this.innerHTML = `<label>${비번}인풋이에요</label><input>`}static get observedAttributes() {return['name'] //name이라는 Attribute가 바뀌는지 감지}attributeChangedCallback(){console.log(1)//바뀌면 이거 실행}}<custom-input name="123"></custom-input>*React, Vue랑 비슷한 재렌더링 기능구현 방법임.
-shadow dom 만드는법
<div id="mordor"></div>document.querySelector('#mordor').attachShadow({mode : 'open'}) //shadowroot 여는 함수document.querySelector('#mordor').shadowRoot.innerHTML ='<p>심연에서왔도다</p>' //shadowRoot공간을 선택한 후 자유롭게 조작가능.shadowRoot를 열어야 숨길태그를 넣을 수 있음 shadow-root공간 안에 p태그 배정 -shadow dom과 Web Component를 같이 쓰면 좋은점 : 스타일 외부 오염 방지
<body><label>dddd</label> //근데 label태그에 준거라서 얘도 빨개짐(스타일 오염)<custom-input name="123"></custom-input><script>class 클래스 extends HTMLElement {connectedCallback() {let name = this.getAttribute('name')this.innerHTML = `<label>${name}인풋이에요</label><input><style>label { color : red }</style> //이런식으로 컴포넌트에 css적용가능`}}
customElements.define('custom-input', 클래스);</script></body>컴포넌트 이외의 태그도 스타일이 적용됨 -해결법 : 커스텀태그 아래에 ShadowDom을 만들면 됨
*Shadow Dom에 넣은것들의 css는 외부에 영향을 주지 않음
<body><label>dddd</label> //여기에 영향안줌<custom-input name="123"></custom-input><script>class 클래스 extends HTMLElement {connectedCallback() {let name = this.getAttribute('name')this.attachShadow({mode : 'open'}) //shadow-root 열기this.shadowRoot.innerHTML = `<label>${name}인풋이에요</label><input><style>label { color : red }</style>` //안에 태그 집어넣기}}
customElements.define('custom-input', 클래스);</script></body>짜잔 - shadow dom과 web Component를 이용해서 HTML을 모듈화 가능
*근데 inherit되는 속성들은 그대로 적용됨.
<template> : HTML 임시보관함. 페이지에 렌더링되지 않음.
<body><label>dddd</label><custom-input name="123"></custom-input><template id="template1"><label>${name}인풋이에요</label><input> //백틱이 적용안되기때문에 ${}는 사용불가<style>label { color : red }</style></template><script>class 클래스 extends HTMLElement {connectedCallback() {let name = this.getAttribute('name')this.attachShadow({mode : 'open'}) //shadow-root 열기this.shadowRoot.append(template1.content.cloneNode(true)) //template1안의 내용 추가}}
customElements.define('custom-input', 클래스);${}는 사용불가 -쉐도우돔 안에 이벤트 리스너도 달기 가능
class 클래스 extends HTMLElement {connectedCallback() {let name = this.getAttribute('name')this.attachShadow({mode : 'open'}) //shadow-root 열기this.shadowRoot.append(template1.content.cloneNode(true))this.shadowRoot.querySelector('label').addEventListener('click',()=>{console.log(1) //shadowRoot에 이벤트리스너 달기도 가능})}}-?. 연산자 (optional chaining) : ?.왼쪽의 자료가 없으면 undefined를 출력
let user = {name : 'kim',age : 30}console.log(user?.name); //'kim'. 근데 의미가 없음. 두번째 점부터 ?.가 유효함(막줄참고)console.log(user.babo?.haha) //undefined. babo라는 키는 없기 때문.console.log(user.babo.haha) //옵셔널 체이닝을 쓰지 않았다면 Error가 뜸console.log(haha?.name) //haha라는 object자체가 없으므로 Errordocument.querySelector('#id')?.innerHTML //여기서도 ?.를 사용가능*중첩된 object자료에서 자료를 뽑을때 자료가 없어도 에러없이 안전하게 자료뽑기 가능.
-??연산자 (nullish) : 왼쪽이 undefined나 null이면 오른쪽을 출력해줌. 아니면 왼쪽.
console.log(undefined ?? '으잉') //?? 왼쪽이 undefined나 null이면 오른쪽을 출력*데이터가 늦게 도착하는경우 undefined가 출력되게 하는 대신에 오른쪽껄 출력하게 만듬.
'개발공부 > JavaScript' 카테고리의 다른 글
23_11_23 JS공부정리 (1) 2023.11.24 23_11_21 JS공부정리 (0) 2023.11.21 23_11_20 JS공부정리 (1) 2023.11.21 23_11_19 JS공부정리 (0) 2023.11.19 23_11_18 JS공부정리 (0) 2023.11.19