lightning web components что это

Русские Блоги

Первое знакомство с веб-компонентом Lightning (lwc)

Когда я работал над проектом Lightning в этом году, внезапно для библиотеки компонентов по умолчанию было выбрано значение lwc, поэтому я начал изучать lwc с любопытством, чтобы делать заметки.

1. Загрузите и установите интерфейс командной строки (CLI).

2. Установите код Visual Studio.

В программной комбинации клавиш Ctrl + Shift + P откройте поисковик:

lightning web components что это

Выберите:SFDX: Create Project.

Затем введите название проекта и нажмите Enter для подтверждения.

Выберите папку для локального сохранения

НажмитеCreate Project

Затем продолжайте Ctrl + shift + P, чтобы открыть поисковик:

ВойтиSFDX: Authorize an Org

Затем введите URL-адрес для входа в проект по умолчанию и подтвердите вход.

Продолжайте открывать поисковик: введитеSFDX: Create Lightning Web Component.

Введите имя компонента, нажмите Enter для подтверждения, проект успешно создан!

lightning web components что это

Щелкните правой кнопкой мыши выбор проектаSFDX: развертывание исходного кода для загрузки организации на сервер организации

Затем вы можете перетащить lwc в конструктор приложений и поместить его на страницу, как показано на рисунке:

lightning web components что это

Анализ кода из 4 частей:

// import module elements
import < LightningElement, track >from ‘lwc’;
// declare class to expose the component
export default class App extends LightningElement <

// add decorator
@track
ready = false;

// use lifecycle hook
connectedCallback() <
setTimeout(() => <
this.ready = true;
>, 3000);
>
>

Атрибут может выбрать только один из @api или @track, но не оба.

apiVersion: обязательно, привязать версию API Salesforce.

isExposed (true или false): чтобы разрешить использование компонента в других пространствах имен, установите только значение true, чтобы компонент можно было использовать в управляемом пакете или использовать Lightning App Builder в другой организации.

target: укажите типы страниц Lightning, на которые можно добавлять компоненты в Lightning App Builder.

targetConfigs: позволяет указать поведение, специфичное для каждого типа страницы Lightning, включая то, какие объекты поддерживают компонент.

6. отправьте код в организацию

7. развернуть файл (при условии, что Dev Hub включен в настройках организации)

1. Сначала проверьте организацию входа:

2. Используйте имя пользователя, чтобы развернуть файл проекта из каталога ebikes-lwc для входа в Dev Hub org (вместо временной org (

3. Установите разрешения в орг.

Источник

Lightning web components что это

Lightning Web Components is a new programming model for building Lightning components. It leverages the web standards breakthroughs of the last five years, can coexist and interoperate with the original Aura programming model, and delivers unparalleled performance.

The 2014 web stack

Until recent years, web standards only offered a limited foundation for the full stack that developers need to build large scale web applications: a rendering engine, standard elements, events, and a core language (ECMAScript 5). In addition to being rudimentary, that foundation had other shortcomings traceable to its roots as a page rendering platform, not an application execution platform. For example:

lightning web components что это

Framework proliferation and fragmentation

As it is often the case, the community and software vendors jumped in to fill the gaps. For example:

In 2014, when we launched the Lightning Component framework along with the Aura programming model, we were part of that effort to push the web forward and enable large scale client-side application development on the web. In the absence of standards, the Lightning Component framework came with its own component model and its own modular programming model.

Although these community and software vendor efforts made it possible to develop large scale client-side apps on the web, they also came with a number of challenges:

Web standards renaissance

This fragmentation underscored the need for standardization and injected new life in the web standards community: the last five years have seen an unprecedented level of innovation and standardization, mostly driven by the W3C/WHATWG and the ECMAScript Technical Committee (TC39) of which Salesforce is a member. The list of standards developed during the last five years includes:

The 2019 web stack

As a result, the web stack looks very different today than it did five years ago, with its weight now heavily tilting towards standards.

lightning web components что это
The core stack finally got the update it needed to become an application development platform in its own right. Many features that required frameworks now come standard: you no longer need a proprietary component model, proprietary language extensions, proprietary modules, etc.

More standards, less frameworks

The standardization of the core stack is incredibly exciting and opens the door to a new breed of frameworks: frameworks whose major task is no longer to fill in the gaps in the core stack, but to provide a thin layer of specialized services on top of a standard stack that is now suitable for large scale app development. The benefits are substantial:

Introducing Lightning Web Components

Lightning Web Components is the Salesforce implementation of that new breed of lightweight frameworks built on web standards. It leverages custom elements, templates, shadow DOM, decorators, modules, and other new language constructs available in ECMAScript 7 and beyond.

lightning web components что это
Lightning Web Components provides a layer of specialized Salesforce services on top of the core stack, including:

Web standards + metadata = unprecedented productivity

Combining the Web Components programming model with the Salesforce metadata and services unleashes an unprecedented level of productivity. For example, the code below creates a form component that has a view and an edit model, knows which type of input to use for each field (combobox, date picker, etc), enforces validation rules, and saves changes in the database without server-side code: five lines of JavaScript and five lines of HTML!

lightning web components что это

Coexistence and interoperability

With the addition of Lightning Web Components, there are now two ways to build Lightning components:

lightning web components что это

Aura components and Lightning web components can coexist and interoperate, and they share the same high level services:

If you are already developing Lightning components with the Aura programming model, you can continue to do so. Your Aura components will continue to work as before. You can build new components with Aura or Lightning Web Components. Your Aura and Lightning Web Components can coexist and interoperate. Over time, you can consider migrating your Aura Components to Lightning Web Components, starting with the components that would benefit the most from the performance benefits of Lightning Web Components.

If you are new to developing on Lightning or if you are starting a new project, we recommend using the Lightning Web Components programming model.

Summary

This is an incredibly exciting time to be a Salesforce developer. With Lightning Web Components, you are using a cutting-edge programming model that is built for the 2019 web stack from the ground up and that interoperates seamlessly with your existing code. With the combination of Lightning Web Components and Salesforce metadata, you get an unprecedented level of productivity, performance and… fun! We can’t wait for you to try it, and we can’t wait to see the amazing apps you’ll build!

Experience enhanced productivity with web standards, speed, and a compatible and easy-to-use framework with Lightning Web Components. Join us on January 23rd for our live Global Broadcast and learn more — register today!

Источник

Explore Lightning Web Components In Salesforce (LWC)

lightning web components что это

Jan 9, 2020 · 19 min read

lightning web components что это

Why Lightning Web Component (LWC)?

Lightning components back in 2014, had extremely limited web standard functionalities, and multiple frameworks came to fulfill the gaps such as ReactJs for virtual DOM, common JS and so on. Aura framework, Angular, and React were part of that initiative, where they pushed web standards to build enterprise applications and these all frameworks became languages. Fast Forward a few years later, Web standard has a rich set of functionalities, supported by Native Browsers such as Templating, Shadow DOM, Custom Element, etc.

Note:- To learn LWC you need elementary knowledge of HTML 5 and ECMAScript 6, so please go through these two first and then come to LWC.

Get Started With LWC.

Prerequisite

Note:- Developer Console has no support for the Lightning web Component. According to salesforce, there is something new to come in replacement of Developer console, so they have to make changes to implement lightning web component so they have no support with a developer console

Step 1:

Open Vs code and check for SFDX, if not install it from the marketplace. To check whether it is installed or not, there are two steps to check that you have all the dependencies for the LWC

Press ctrl+shift+p (for MAC OS press cmd+shift+p) and type “sfdx” you should see something like this if not install a salesforce extension pack from the marketplace.

Open the terminal of vscode by pressing ctrl+` and type sfdx — version

You should see the version of CLI if not install salesforce CLI

Step 2:

First, create an sfdx project by pressing ctrl+shift+p (for MAC OS press cmd+shift+p) and type,

press enter and give the name and location of the project. A new window of Vscode Will be opened with the workspace contacting the folder where the project is created in that folder, there would be some configuration files and folders which thereby default in an sfdx project.

Step 3:

The next step is to Authorize a salesforce org. I am using scratch org for this, but you can also use your developer org.

To Authorize the developer org, you need to press ctrl+shift+p (for MAC OS press cmd+shift+p) and type,

and select the type of Org you want to Authorize. If it is a developer org use production and if it is a sandbox org, use Sandbox and complete the web authentication. After logging in come back to vs code, and you will successfully be connected to the org

To use scratch org, you first need to Authorize a dev hub org by pressing ctrl+shift+p (for MAC OS press cmd+shift+p) and type,

then log in to dev hub enabled account.

Now create a scratch org by pressing ctrl+shift+p (for MAC OS press cmd+shift+p) and type,

select the package.json file and press enter. Now insert the name of scratch org and press enter then select the number of days you want your scratch org to be activated, after this period of time, the scratch org will automatically deprecate, and you can select from 1 to 30 days of scale. wait for the process to complete. After completing the process the scratch org is created successfully.

To see all the orgs connected with your SFDX, open the terminal of vs code and type,

and press enter, you will see all the connected orgs and scratch orgs.

To login into the scratch org open the terminal and type,

and press enter and the scratch org will automatically login into your default browser without any username and password.

Step 4:

After you are connected with your scratch org, come back to vscode we will create a Lightning App so that we can run our lightning web component in a Lightning App. To create a lightning app press ctrl+shift+p (for MAC OS press cmd+shift+p) and type

and press enter. Select the desired directory (you can select the default directory as well) press enter. Name the Lightning app and press enter. After the process is finished a lightning app is created in our local directory open App-Name.app file replace the code with this

To add this to our scratch org open the terminal and type

And wait while the SFDX pushes your code to scratch org, after completing the process you will see something like this

Now that you have successfully deployed the Lightning app to the scratch org, go to the developer console of scratch org and open lightning component, you will see your app there and run the app to see the output.

Step 5:

press ctrl+shift+p (for MAC OS press cmd+shift+p) and type

press enter. Then enter the desired name your lightning web component and press enter. choose your desired location (you can select the default location as well) and press enter. Now wait for the process to complete and automatically LWC files are opened

LWC files contain

A HTML file

A JS file

A Metadata file

If you get a closer look at the Js file you will see that there are some warnings, this is because some keywords are new in ES6 and only supported by ES6 and according to the current browser scenario the browser uses ES5. To remove this warning just add this comment on the top

This comment removes the unwanted warning that JShint is giving us.

Let us create A Hello World Program for LWC

Replace HTML File with this code

Replace JS file with this code

Replace the Metadata File with the code

Replace the Lightning App with this code

Connect LWC With Apex class.

Previously we created a hello world component, but the real-world scenarios are more complex than writing a HelloWorld program. So now let us search for some Accounts from our salesforce org. To make this component, we have to query Accounts from our Salesforce org for which we have to make an apex class, and connect apex class with our LWC. This shows how to connect an apex class with our LWC and how to make a component that searches the Accounts From our Salesforce Org.

Step 1.

Create an Apex Class Using Sfdx. To create an Apex class press ctrl+shift+p (for MAC OS press cmd+shift+p) and type,

and press enter. Enter your desire Apex class name for this please Enter AccountController. Then select your desired directory I would suggest using default directory and press enter. Replace the code with this code

Step 2.

Now we have to create a search Card which would appear when a user enters something in the input box to search so we have to create a Lightning web Component by pressing ctrl+shift+p (for MAC OS press cmd+shift+p) and type,

and name the component as AccountCard and replace the code as below :

Step 3.

Now let’s create the main component of account search. Press ctrl+shift+p (for MAC OS press cmd+shift+p) and type,

and name the component as SearchAccountRecords and replace the code as below

Step 3.

Add this component to the lightning App so that we can view what we have made and replace the code of the lightning app with this

Now push this code to the scratch org. To push the code, open terminal and write,

and press enter. After it is completed, the code is pushed to scratch org, then refresh the app page and you will see this output:

Playing With Event Is always Fun right?

Events in Lightning web components are built on DOM Events, a collection of APIs and objects available in every browser.

The DOM events system is a programming design pattern that includes these elements.

To create events, we strongly recommend using the CustomEvent interface. In Lightning web components, CustomEvent provides a more consistent experience across browsers including Internet Explorer. It requires no setup or boilerplate, and it allows you to pass any kind of data via the detailed property which makes it flexible.

Lightning web components implement the EventTarget interface which allows them to dispatch events, listen for events, and handle events.

Create and dispatch events

Create and dispatch events in a component’s JavaScript class. To create an event, use the CustomEvent() constructor. To dispatch an event, call the EventTarget.dispatchEvent() method.

The CustomEvent() constructor has one required parameter which is a string indicating the event type. As a component author, you name the event type when you create the event. You can use any string as your event type. However, we recommend that you confirm with the DOM event standard.

Note:- Don’t prefix your event name with the string on, because inline event handler names must start with the string on. If your event is called onmessage, the markup would be

Notice the doubled word ‘onon’, which is confusing.

Let’s jump into some code.

The c-paginator component contains Previous and Next buttons. When a user clicks the buttons, the component creates and dispatches previous and next events. You can drop the paginator component into any component that needs Previous and Next buttons. That parent component listens for the events and handles them.

The c-paginator component contains Previous and Next buttons. When a user clicks the buttons, the component creates and dispatches previous and next events. You can drop the paginator component into any component that needs Previous and Next buttons. That parent component listens for the events and handles them.

Now let’s create the paginator component: press ctrl+shift+p (for MAC OS press cmd+shift+p) and type,

and name the component as paginator and replace the code as below

When a user clicks a button, the previousHandler or nextHandler function executes. These functions create and dispatch the previous and next events.

Now let’s create the main component of event press ctrl+shift+p (for MAC OS press cmd+shift+p) and type,

and name the component as eventsimple and replace the code as below

When c-event-simple receives the previous and next events, previousHandler and nextHandler increase and decreases the page number. Because the page property is tracked, when its value changes it causes the template to rerender.

Pass Data in an Event

To pass data up to a receiving component, set a detail property in the CustomEvent constructor. Receiving components access the data in the detail property in the event listener’s handler function.

WARNING The CustomEvent interface imposes no type requirements or structure on the detail property. However it’s important to send only primitive data.JavaScript passes all data types by reference except for primitives. If a component includes an object in its detail property, any listener can mutate that object without the component’s knowledge. This is a bad thing! It’s a best practice either to send only primitives, or to copy data to a new object before adding it to the detailed property. Copying the data to a new object ensures that you’re sending only the data you want and that the receiver can’t mutate your data.

Create an Apex Class Using Sfdx. To create an Apex class press ctrl+shift+p (for MAC OS press cmd+shift+p) and type,

and press enter. Enter your desire Apex class name for this please Enter ContactController. Then select your desired directory, I would suggest using a default directory and press enter. Replace the code with this code.

Now let’s create the component press ctrl+shift+p (for MAC OS press cmd+shift+p) and type,

and name the component as contactListItem and replace the code as below :

Each item in the list of contacts is a nested c-contact-list-item component.
The c-contact-list-item component wraps the contact name in an anchor tag with an onclick event listener that executes the selectHandler function.

When a user clicks to select a contact, the component creates and dispatches a CustomEvent called selected. The event includes the data detail: this.contact.Id, which is the ID of the selected contact. The parent, c-event-custom, use the contact reference to display more information about the contact.

The c-event-with-data component listens for the selected event in the onselected attribute and handles it in the contactSelected event handler.

Now let’s create the component press ctrl+shift+p (for MAC OS press cmd+shift+p) and type,

and name the component as eventWithData and replace the code as below

In the contact selected event handler, the component assigns the event, detail property to the contact Id property. It finds the contact with that ID in the contacts array provisioned via @wire, and displays the contact’s name, title, phone, and email in the template.

Configure Event Propagation

After an event is fired, it can propagate up through the DOM. To understand where events can be handled, understand how they propagate. Lightning web component events propagate according to the same rules as DOM events. When you create an event, define event propagation behavior using two properties on the event, bubbles and composed.

A Boolean value indicating whether the event bubbles up through the DOM or not. Defaults to false.

A Boolean value indicating whether the event can pass through the shadow boundary. Defaults to false.

The framework uses a Shadow DOM to encapsulate components.

bubbles: false and composed: false

The default configuration. The event doesn’t bubble up through the DOM and doesn’t cross the shadow boundary. The only way to listen to this event is to add an event listener directly to the component that dispatches the event.

This configuration is recommended because it’s the least disruptive.

bubbles: true and composed: false

The event bubbles up through the DOM but doesn’t cross the shadow boundary.

There are two ways to bubble up an event:

To bubble an event inside the component’s template, dispatch the event on an element in the template. The event bubbles up to the element’s ancestors inside the template. When the event reaches the shadow boundary, it stops.

bubbles: true and composed: true

The event bubbles up through the DOM, crosses the shadow boundary, and continues bubbling up through the DOM to the document root. Because this configuration bubbles your event all the way to the document root, it can cause name collisions. Name collisions can cause the wrong event listeners to fire.

bubbles: false and composed: true

Lightning web components don’t use this configuration.

DOM Event Propagation Phases

The standard DOM Events describes 3 phases of event propagation:

Here’s the picture of a click on

inside a table, taken from the specification:

That is: for a click on

the event first goes through the ancestors chain down to the element (capturing phase), then it reaches the target and triggers there (target phase), and then it goes up (bubbling phase), calling handlers on its way.

Before we only talked about the bubbling, because the capturing phase is rarely used. Normally it is invisible to us.

To catch an event on the capturing phase, we need to set the handler capture option to true:

There are two possible values of the capture option:

Note that while formally there are 3 phases, the 2nd phase (“target phase”: the event reached the element) is not handled separately: handlers on both capturing and bubbling phases trigger at that phase.

Let’s see both capturing and bubbling in action:

Event Propagation Phases In LWC

There are two important things to notice.

In the absence of other influences, an event travels all the way down the component hierarchy, and then all the way back up, visiting each DOM element on the path through the hierarchy. Each element along the path of that component can listen for the event, and then handle the event or stop further propagation.

In practice, when your component fires an event configured for the bubble phase (< bubbles: true, composed: true >), you can ignore the capture phase (steps 1–3). Simply think of the event’s path as starting with your component, and then moving to its parent, and then grandparent, and so on (steps 4–6). Dispatching events or adding listeners to the capture phase is not supported.

Shadow DOM

The elements in each Lightning web component are encapsulated in a shadow tree. This part of the DOM is called a shadow tree because it’s hidden from the document that contains it. The shadow tree affects how you work with CSS, events, and the DOM.

Shadow DOM is a web standard that encapsulates the elements of a component to keep styling and behavior consistent in any context. Since not all browsers that Salesforce supports implement Shadow DOM, LWC uses a shadow DOM polyfill. A polyfill is code that allows a feature to work in a web browser.

To better understand how to work with the shadow tree, let’s look at some markup. This markup contains two Lightning web components: c-app and c-item. The shadow root defines the boundary between the DOM and the shadow tree. This boundary is called the shadow boundary.

Let’s look at how to work with the shadow tree in each of these areas.

CSS styles defined in a parent component don’t leak into a child. In our example, a p style defined in the App.css style sheet doesn’t style the p element in the c-item component, because the styles don’t reach into the shadow tree.

To prevent exposing a component’s internal details, if an event bubbles up and crosses the shadow boundary, some property values change to match the scope of the listener.

Now let us create a Lightning web component which demonstrates bubbling and shadow root press ctrl+shift+p (for MAC OS press cmd+shift+p) and type sfdx: create Lightning Web Component and name the component as contactListItemBubbling and replace the code as below

press ctrl+shift+p (for MAC OS press cmd+shift+p) and type,

and name the component as eventBubbling and replace the code as below

Author Bio

My name is Sourabh Kumawat and I work as an Associate Software Engineer at Techcoopers powered by Selectiva Inc. which is a Custom Software Development Company. I have worked on various technologies such as Salesforce and various frameworks of Javascript. I believe in exploring and learning new technologies. Also, I am always excited to share the knowledge I have.

Sourabh Kumawat

Salesforce Development | Salesforce Administrator | JavaScript | ReactJS | React Native | NodeJS | Visual Studio Code Extension

Источник

Добавить комментарий

Ваш адрес email не будет опубликован. Обязательные поля помечены *