LWC에서 자주 쓰는 표현들

ahncheer·2023년 7월 27일
1

LWC & LWR

목록 보기
39/45

개인적으로 자주 쓰는 표현들 정리

● html

*선택문

<template lwc:if={property1}>
    Statement1
</template>
<template lwc:elseif={property2}>
    Statement2
</template>
<template lwc:else>
    Statement3
</template>

*반복문

<ul>
    <template for:each={contactsList} for:item="item" for:index="index">
    <li key={item.id}>
            {item.name}
    </li>
    </template>
</ul>

● JS

console.log('▶ result : ', JSON.parse(JSON.stringify(result)));

*반복문

testList.forEach((el, index) => {  }); 

*값이 포함되어있는지 찾기

// Array의 경우 
let testList = ['a', 'b', 'c'];
let a01 = testList.includes('a'); // includes(undefined)는 true로 나오니 주의
let a02 = testList.indexOf('a') >= 0;
console.log('a01 : ', a01);
console.log('a02 : ', a02);

// 두개의 Array 비교
let arr1 = [1, 2, 3];
let arr2 = [2, 3];
// 하나라도 포함되어 있는지 
let isFounded = arr1.some( ai => arr2.includes(ai) );
// arr2의 모든 값이 같은지 
let allFounded = arr2.every( ai => arr1.includes(ai) );
console.log('isFounded : ', isFounded);
console.log('allFounded : ', allFounded);

// ArrayList의 경우
const arrList = [ {label: 'a'}, {label: 'b'}, {label: 'c'} ];
let b01 = arrList.some(item => item.label === 'b');
let b02 = arrList.findIndex((x) => x.label === 'b') >= 0;
console.log('b01 : ', b01);
console.log('b02 : ', b02);

*클래스 관련

// 클래스 명으로 찾기 
let childContent = this.template.querySelectorAll('.test');
let childContent = alertModal.querySelector(".test");

// 클래스를 포함하고 있는지 확인하기 
item.classList.contains("active");

// 클래스 추가, 삭제, 토글
childContent.classList.add("active");
childContent.classList.remove("active");
childContent.classList.toggle("active");

* 비동기 처리

getResult(params) {
    return new Promise(async(resolve) => {
        this.showSpinner = true;
        try {
        let result = await getAllResult(params);
        console.log(' ▶▶ getResult : ', JSON.parse(JSON.stringify(result)));

        resolve(result);
        } catch(error) {
            console.error(error);
            if(error.body) alert(error.body.message);
        } finally {
            this.showSpinner = false;
        }
    });
}

// 간단하게
async function getResult() {
  let res = await getAllResult();
  console.log(' ▶▶ getResult : ', JSON.parse(JSON.stringify(res)));
}

* get, set

@api /* disabled 세팅 */
get disabled() {
    return this._disabled;
}
set disabled(value) {
    this._disabled = value;
}

* 자주 사용하는 import

// 컨트롤러 연결
import getAllResult from '@salesforce/apex/apex파일이름.함수?이름';

// 페이지 이동시 필요
// 추가시 'export default class 컴포넌트이름 extends NavigationMixin(LightningElement)'로 변경

import { NavigationMixin } from 'lightning/navigation';

// 사이트 설정 관련 
import isGuest from '@salesforce/user/isGuest';
import lang from '@salesforce/i18n/lang';

외부 페이지 링크 함수

import { NavigationMixin } from 'lightning/navigation';

// 외부 페이지 링크 함수
const externalNavigation = (_this, url) => {
    _this[NavigationMixin.Navigate]({
        type: 'standard__webPage',
        attributes: {
            // url: '/industry' or https://www.naver.com
            url: url,
        }
    });
}

Render 이후 한번만 실행

@track isFirstRender = true;
renderedCallback() {
    if(this.isFirstRender) {
        // 여기에 실행 

        this.isFirstRender = false;
    }
}

● CSS

/* 배경 반복 */
.bg-img{
    background-size: cover;
    background-repeat: no-repeat;
    background-position: center center;
}
profile
개인 공부 기록용.

1개의 댓글

comment-user-thumbnail
2023년 7월 27일

공감하며 읽었습니다. 좋은 글 감사드립니다.

답글 달기