Lightning Web Components Basics

HeyDude·2023년 9월 18일
0

Salesforce-LWC

목록 보기
2/2

2023-09-15

Discover Lightning Web Components

Trailhead: https://trailhead.salesforce.com/content/learn/modules/lightning-web-components-basics/discover-lightning-web-components

학습목표:
1. Lightning Web Components 프로그래밍 모델을 설명할 수 있다.
2. LWC를 사용함에 얻는 이점들을 나열할 수 있다.
3. LWC개발을 시작하기 위해 무엇이 필요한지 찾을 수 있다.

Why LWC?

현대 브라우저들은 웹 표준을 기반으로 하고 있으며, 웹 표준은 점점 발전하여 브라우저가 유저들에게 제공할 수 있는 것들을 점차 늘리고 있다.

LWC는 Web Components 표준을 사용하며 브라우저에서 natively하게 동작하는 코드로 작성이 된다. https://github.com/WICG/webcomponents

간단한 Component 생성하기

웹표준을 사용함으로써 얻는 이점은 간단함이다. LWC를 사용한 component 생성은 딱 세개가 필요하다. Javascript 파일, HTML 파일, 그리고 css 파일.

HTML - the structure for your component
Javascript - for core logic and event handling
CSS - to make it look better :)

간단한 예시로 시작하겠다.
HTML

<template>
	<input value={message}></input> 
</template>

<template> 태그는 그 component의 HTML의 가장 기초의 block이다. 이 안에 여러 HTML태그들을 넣을 수 있다.

JS

import { LightningElement } from 'lwc'; 

export default class App extends LightningElement {
	message = 'Hello World'; 
}

CSS

input { color: blue; }

LWC를 개발하기 위해 알면 좋은것들

  • Dev Hub & Scratch Org: Scratch Org는 일회용 salesforce org로 개발 및 테스트에 용이. Dev Hub는 여러 scratch ogr들을 관리할 수 있음.
  • Lightning Component Library

추가적으로 더 볼 reference들

LDS (Lightning Data Service)
https://developer.salesforce.com/docs/platform/lwc/guide/data-ui-api?-ga=2.244483405.978196274.1694480671-1572924634.1694480671.html

Lightning Locker
https://developer.salesforce.com/docs/platform/lwc/guide/security-locker-service?-ga=2.244483405.978196274.1694480671-1572924634.1694480671.html

Create Lightning Web Component

Trailhead: https://trailhead.salesforce.com/content/learn/modules/lightning-web-components-basics/create-lightning-web-components

목표:
1. 각 component 파일의 내용들을 기술할 수 있다.
2. Javascript method들을 만들 수 있다.
3. Javascript component의 Lifecycle hook을 사용할 수 있다.

HTML

  • <template> 태그를 반드시 포함한다.
  • <template> 태그 안에 html 태그들을 넣는다.
  • LWC는 기본적인 요소들을 만들 필요없이 가져다 쓸수있도록 Component Library를 가지고 있다.
  • {} 안에 있는 식별자들은 상응하는 javascript 파일에서 같은 이름의 필드들과 매칭된다 (바운딩)
  • 조건을 걸때 lwc:iflwc:else를 통하여 html파일안에서 사용할 수 있다.

LWC Module

  • LWC는 core functionality를 묶기위해 모듈을 사용한다.
  • LWC의 코어 모듈은 lwc이다.
  • import { LightningElement } from 'lwc';
  • LightningElement는 LWC를 사용하기 위한 기본적인 class이다. connectedCallback()메서드를 사용하기 위해 필요하다.
  • connectedCallback()은 component가 DOM에 생성될 때 발동한다.

Lifecylce Hooks

LWC는 한 component의 lifecycle에서 중대한 이벤트들이 발생했을 때 동작시킬 수 있는 여러 method들을 지원한다. 그 이벤트들은 대략 다음과 같다.

한 Component가

  • 생성될때
  • DOM에 추가될때
  • 브라우저에 렌더링 될때
  • 에러 발생시
  • DOM에서 지워질때

callback 메서드들을 통해 위의 생명주기 이벤트들중 어느것에라도 반응할 수 있다.
예를 들어 위에서 잠깐 언급한 connectedCallback() 메서드의 경우, 그 컴포넌트가 DOM에 삽입될때 동작한다.

그리고 this라는 키워드를 자주 사용하게 될것인데 이것은 현재 context의 top level을 지정할 때 쓰인다.

Decorators

Decorators는 어떤 프로퍼티나 function의 동작을 바꾸기 위해 종종 쓰인다.
Decorator를 사용하기 위해서는 사용하고자 하는 특정 데코레이터를 lwc로부터 import 해야한다. 그리고 그것을 프로퍼티 전에 위치시킨다.

Example:

import { LightningElement, api } from 'lwc';
export default class MyComponent extends LightningElement{ 
	@api message;
}

위 예제에서, api decorator를 가져와서 사용하는 모습이다.

여러 decorator들을 가져올 순 있지만, 사용할 때는 여러개를 하나의 function 이나 property에 적용할 수 없다.

다음은 몇가지 lwc decorator들에 대한 설명이다.

@api
하나의 필드를 public으로 표시한다. Public property는 한 component의 API를 정의한다. 예를 들어, 부모 LWC에서 자식 LWC의 property에 접근해야할 때, 이 decorator를 사용한다.
Public property는 반응적(reactive)이다.

LWC Event Handling

Trailhead: https://trailhead.salesforce.com/ko/content/learn/modules/lightning-web-components-basics/handle-events-in-lightning-web-components

위 트레일헤드 사이트에서 예제파일들을 다운로드 한다.
다음과 같은 구조로 nested되어있는 LWC 파일들이다.

먼저 selector component 파일을 살펴보자. 다음과 같이 이 일종의 컨테이너 컴포넌트는 다른 child LWC component들을 호출한다.

        <main class="main" >

            <c-list onproductselected={handleProductSelected}></c-list>

        </main>

        <aside class="sidebar-second">

            <c-detail product-id={selectedProductId}></c-detail>

        </aside>

<c-xxxx> 라는 태그를 이용하여 호출을 하며 만약 자식의 이름이 Camel-case로 되어있다면 대문자 앞에서 -를 사용하며 소문자로 바꿔준다.
ex) 만약 myFunctionGood 이라는 컴포넌트를 호출하려면, <c-my-function-good> 이라는 태그 사용한다.

Events Up, Properties Down

만약 한 Component가 여러 Parent와 Child를 같이 포함하고 있는 경우, 컴포넌트들은 Up-Down 형식으로 소통하게된다.

  1. 자식 component(c-todo-item)은 부모인 c-todo-app으로 event를 발행할 수 있다. 예를 들어 자식 컴포넌트의 버튼이 클릭된 경우, event object를 부모로 보내 부모측에서 event handling을 할 수 있다.

  2. 부모 component는 property를 보내거나, 자식측에 있는 메서드를 실행시킬 수 있다. 예를 들어, 부모에서 자식으로 어떤 text value를 보내거나, 자식 js파일에 정의된 함수를 호출 할 수 있다.

Passing Information Up

Information은 event와 event listener를 통해 위로 전달될 수 있다.
(참조: [[LWC Event]])

The child component dispatches the event and the parent component listens for it.

Dispatching a event 라는 행위는 부모 component로 보낼 수 있는 event object를 생성하는 것까지 포함한다.

이때 부모는 해당하는 event의 handler를 가지고 있어야 그 event에 반응할 수 있다.

ex) 자식component에서 간단한 event를 dispatch 하는 방식.

nextHandler() { 
	this.dispatchEvent(new CustomEvent('next')); 
}

ex) 부모 component에서 next라는 event를 받고 로직을 수행할 handler를 등록하는 모습.

<!-- todoApp.html -->
<template>
  <c-todo-item onnext={nextHandler}></c-todo-item>
</template>

// todoApp.js
import { LightningElement } from 'lwc';
export default class TodoApp extends LightningElement {
  ...
  nextHandler(){
    this.page = this.page + 1;
  }
}

Passing Information Down

LWC에서 Information Down은 public properties와 public methods를 통해 구현된다.
(참고: [[LWC Public Property and Method]])

Public property는 @api decorator를 통해 만들 수 있다. 해당 decorator가 선언된 property는 부모로부터 값을 전달받을 수 있다.

Public properties are great solutions for passing down primitive values, simple objects, and arrays.

ex) 자식 js파일

// todoItem.js 
import { LightningElement, api } from 'lwc'; 
export default class TodoItem extends LightningElement { 
	@api itemName; //이 property를 public으로 선언함.
}

ex) 부모에서 자식 public property에 값을 할당하는 모습

<!-- todoApp.html -->
<template>
  <c-todo-item item-name="Milk"></c-todo-item>
</template>

Getter와 setter를 사용할 수도 있다.

또한 자식의 method들 중 @api로 선언된 것들은 부모로부터 부를 수가 있다.

// videoPlayer.js - Child LWC
import { LightningElement, api } from 'lwc';
export default class VideoPlayer extends LightningElement {
  @api
  play() {
    // Play music!
  }
}

// methodCaller.js - Parent LWC
import { LightningElement } from 'lwc';
export default class MethodCaller extends LightningElement {
  handlePlay() {
    this.template.querySelector('c-video-player').play();
  }
}

Styling and Getting data from a Salesforce

Add a Style to LWC

CSS는 같은 이름의 css파일을 폴더 안에 만들어 스타일을 적용할 수 있다.
Salesforce는 SLDS라는 이름의 일종의 CSS Framework를 제공하므로 이를 사용한다면 Salesforce Lightning과 조화되는 디자인을 빠르게 구현할 수 있다.

Get Salesforce Data

Salesforce Org로 부터 데이터를 pull 하는 방법을 소개한다.
LWC는 반응적인 wire service를 사용한다. 이는 LDS에 기반한다.

@wire decorator를 사용해 데이터를 가져와보자.

profile
어제보다 나은 오늘의 내가 되고자 노력하는 개발자

0개의 댓글