Salesforce LWC learning (seven) Navigation & Toast

Previous we introduced the relevant service for LWC commonly used LDS adaptation of wire service and @salesforce module, in fact, LWC also provides other useful service, such as for navigation-related Lightning / Navigation and Display toast message related Lightning / platformShowToastEvent. Cipian mainly for the two brief service.

一. lightning/navigation

We have a lot of scenes will be used to jump operations, such as after creating a record jump to record details page, click on the link to jump directly to the download page or download the file, jump to a list, and so on. LWC encapsulates lightning / navigation service to achieve the relevant jump operation. Of course, this service in addition to the package associated with the jump function, but also encapsulates PageReference obtain the current function. Shown as follows.

1. CurrentPageReference: This method is used to obtain a reference to the current page, use the following statement will be able to get a reference to the current page. If we want to edit its parameter key-value pairs, we need to update the current page reference of Page state. As for how to update, the following will be introduced.

1 import { CurrentPageReference } from 'lightning/navigation';
2 @wire(CurrentPageReference)
3 pageRef;

PageRef returned to PageReference variables. Js PageReference encapsulated object, there are three variables.
1) type: the current PageReference type. lwc encapsulates the following types:

  • Lightning Component
  • Knowledge Article
  • Login Page
  • Named Page
  • Navigation Item Page
  • Object Page
  • Record Page
  • Record Relationship Page
  • Web Page

These details can be found in PageReference: https://developer.salesforce.com/docs/component-library/documentation/lwc/lwc.reference_page_reference_type
we often have Lightning Component / Object Page / Record Page / Record Relationship Page / Web Page.
2) attribute: declare different types of PageReference create PageReference you need to configure different attribute, attribute configuration details see the same link above.

3) state: is used to store the key value of the parameter type. We may pass parameters in the URL, use CurrentPageReference acquired PageReference in, state storage is part of its argument.

The following demo to a better understanding of usage and returns the contents.

getCurrentPageReferenceDemo.js: loading CurrentPagReference, assigned to the reference PAGEREF;
 1 import { LightningElement, wire } from 'lwc';
 2 import {CurrentPageReference} from 'lightning/navigation';
 3 export default class GetCurrentPageReferenceDemo extends LightningElement {
 4     @wire(CurrentPageReference)
 5     pageRef;
 6 
 7     get currentPageInfo() {
 8         if(this.pageRef !== undefined) {
 9             return JSON.stringify(this.pageRef);
10         }
11         return '';
12     }
13 }

getCurrentPageReferenceDemo.html:

1 <template>
2     {currentPageInfo}
3 </template>

Show Results: We refer to this component contacts on the inside pages of details, and manually set the parameter for the URL details page of returned results as shown below.

 2. NavigationMixin: Use this adapter to achieve the skip function. This adapter encapsulates two jump API implementation.

  • [NavigationMixin.Navigate](pageReference, [replace]) - a component in an application calls this API to jump to another page;
  • [NavigationMixin.GenerateUrl](pageReference) - component calls this API to get the URL Promise need to jump.

Both API, first call GenerateUrl get to the Promise, then use the Navigate an API can be realized jump. You need to be introduced in the head before we use this service, and the other difference is that we also need to inherit the class javascript in NavigationMixin.

import { NavigationMixin } from 'lightning/navigation';
export default class MyCustomElement extends NavigationMixin(LightningElement) {}

The above two API we can also see pageReference parameter, and returns the same value CurrentPageReference above type, are encapsulated CurrentPageReference javascript objects. We can use plain object to splice variables of this object. He said comparison around, following by an official demo will be able to better understand.

 navigationLineExample.js: Promise PageReference declared in connectedCallback life cycle, the time for handleClick to trigger.

 1 import { LightningElement, track } from 'lwc';
 2 import { NavigationMixin } from 'lightning/navigation';
 3 
 4 export default class NavigationLinkExample extends NavigationMixin(LightningElement) {
 5     @track url;
 6 
 7     connectedCallback() {
 8         // Store the PageReference in a variable to use in handleClick.
 9         // This is a plain Javascript object that conforms to the
10         // PageReference type by including "type" and "attributes" properties.
11         // The "state" property is optional.
12         this.accountHomePageRef = {
13             type: "standard__objectPage",
14             attributes: {
15                 "objectApiName": "Account",
16                 "actionName": "home"
17             }
18         };
19         this[NavigationMixin.GenerateUrl](this.accountHomePageRef)
20             .then(url => this.url = url);
21     }
22 
23     handleClick(evt) {
24         // Stop the event's default behavior.
25         // Stop the event from bubbling up in the DOM.
26         evt.preventDefault();
27         evt.stopPropagation();
28         // Navigate to the Account Home page.
29         this[NavigationMixin.Navigate](this.accountHomePageRef);
30     }
31 }

navigationLineExample.html: Click the button to trigger handleClick method

1 <template>
2     <div>
3         <a href={url} onclick={handleClick}>Account Home</a>
4     </div>
5 </template>

The demo configuration record page account of by the above demo we will be able to achieve the jump to the function of Account home page, you can also see the magic statement PageReference the type and attributes of. After only need to understand the principles we can achieve more by changing PageReference Type and its corresponding attribute, junior partner interested can try on their own.

 When we jump or self-refresh, sometimes we need to pass parameters, in the above LWC also mentioned the use of state variables to pass parameters, before we update this variable to find out the relevant restrictions and requirements.

  • pagereference object has been frozen, so you can not change it directly. If we want to jump to a same page and this page contains already updated state, we need to look at current copy of this PageReference then use the Object . ASSIGN ( { } , pageReference ) way to update the state, if the jump to different pages, we only need to create plain PageReference time can pass in, I said there would be no restrictions at this point.
  • state variables when building key-value pair, the key must be used together with two underscores __ namespace as a prefix, if not managed package, then the namespace is c, for example, we want to pass testParam value testValue. Construction of the key-value be state.c__testParam = testValue;
  • state variable value key-value pairs must all be of type string as key variables for each state can be serialized to a URL query parameter.
  • If you want to delete a key state for only you need to set the value to undefined.

We can see by the above 1,2,3,4 point, the restricted 1, 2, 3 belongs to specification. We directly for the state to jump to other pages, if the first point for the jump to the current page, just change the parameters, we need to consider the above. Provided by the official demo can better understand the process for the parameter.

 pageStateChangeExample.js: When demo in consideration of the current page to jump to just deal with changing parameters. At this point pagereference been frozen, can only be addressed through Object.assign method.

 1 import { LightningElement, wire, track } from 'lwc';
 2 import { CurrentPageReference, NavigationMixin } from 'lightning/navigation';
 3 
 4 export default class PageStateChangeExample extends NavigationMixin(LightningElement) {
 5 
 6     // Injects the page reference that describes the current page
 7     @wire(CurrentPageReference)
 8     setCurrentPageReference(currentPageReference) {
 9         this.currentPageReference = currentPageReference;
10 
11         if (this.connected) {
12             // We need both the currentPageReference, and to be connected before
13             // we can use NavigationMixin
14             this.generateUrls();
15         } else {
16             // NavigationMixin doesn't work before connectedCallback, so if we have 
17             // the currentPageReference, but haven't connected yet, queue it up
18             this.generateUrlOnConnected = true;
19         }
20     }
21     @track
22     showPanelUrl;
23 
24     @track
25     noPanelUrl;
26 
27     // Determines the display for the component's panel
28     get showPanel() {
29         // Derive this property's value from the current page state
30         return this.currentPageReference &&
31             this.currentPageReference.state.c__showPanel == 'true';
32     }
33 
34     generateUrls() {
35         this[NavigationMixin.GenerateUrl](this.showPanelPageReference)
36             .then(url => this.showPanelUrl = url);
37         this[NavigationMixin.GenerateUrl](this.noPanelPageReference)
38             .then(url => this.noPanelUrl = url);
39     }
40 
41     // Returns a page reference that matches the current page
42     // but sets the "c__showPanel" page state property to "true"
43     get showPanelPageReference() {
44         return this.getUpdatedPageReference({
45             c__showPanel: 'true' // Value must be a string
46         });
47     }
48 
49     // Returns a page reference that matches the current page
50     // but removes the "c__showPanel" page state property
51     get noPanelPageReference() {
52         return this.getUpdatedPageReference({
53             // Removes this property from the state
54             c__showPanel: undefined
55         });
56     }
57 
58     // Utility function that returns a copy of the current page reference
59     // after applying the stateChanges to the state on the new copy
60     getUpdatedPageReference(stateChanges) {
61         // The currentPageReference property is read-only.
62         // To navigate to the same page with a modified state,
63         // copy the currentPageReference and modify the copy.
64         return Object.assign({}, this.currentPageReference, {
65             // Copy the existing page state to preserve other parameters
66             // If any property on stateChanges is present but has an undefined
67             // value, that property in the page state is removed.
68             state: Object.assign({}, this.currentPageReference.state, stateChanges)
69         });
70     }
71 
72     connectedCallback() {
73         this.connected = true;
74         
75         // If the CurrentPageReference returned before this component was connected,
76         // we can use NavigationMixin to generate the URLs
77         if (this.generateUrlOnConnected) {
78             this.generateUrls();
79         }
80     }
81 
82     handleShowPanelClick(evt) {
83         evt.preventDefault();
84         evt.stopPropagation();
85         // This example passes true to the 'replace' argument on the navigate API
86         // to change the page state without pushing a new history entry onto the
87         // browser history stack. This prevents the user from having to press back
88         // twice to return to the previous page.
89         this[NavigationMixin.Navigate](this.showPanelPageReference, true);
90     }
91 
92     handleNoPanelClick(evt) {
93         evt.preventDefault();
94         evt.stopPropagation();
95         this[NavigationMixin.Navigate](this.noPanelPageReference, true);
96     }
97 }

pageStateChangeExample.html: for the treatment of showPanel and noPanelUrl

<template>
    <div>
        <a href={showPanelUrl} onclick={handleShowPanelClick}>Show Panel</a>
    </div>
    <div if:true={showPanel}>
        <h1>This is the panel</h1>
        <a href={noPanelUrl} onclick={handleNoPanelClick}>Hide Panel</a>
    </div>
</template>

 二. Lightning/platformShowToastEvent

When we DML operations or some scene or validation need to show some of the information, of course, we can show by ligtning-messages information on the page, another way you can use toast message displayed only a few seconds and then disappears style. LWC provides lightning / platformShowToastEvent implement this feature. Module encapsulates ShowToastEvent event, after the instantiation dispatchEvent can be used.

ShowToastEvent following events several parameters

  • title: toast header section, showing the header area;
  • message: the content portion of toast. This message can be a text, the text may be a place holder comprises, typically place holder URL or text;
  • messageData: {} When the message contains time place holder, using messageData replacement;
  • variant: toast the show's theme and icon styles. There are several values ​​to choose from: info / success / warning / error. We can show different variant on display according to different scenarios;
  • mode: used to determine how long to show toast. There are several values ​​to choose from: dismissable / pester / sticky. dismissable is the default value, functionality for user clicks the close button or after 3 seconds later toast disappeared; pester for display only 3 seconds, 3 seconds later disappear (this is not a close button); sticky for only the user clicks the close button only It will disappear.

We show this usage in recordEditFormSample.

 1 <template>
 2     <lightning-record-edit-form
 3         record-id={recordId}
 4         object-api-name={objectApiName}
 5         onsubmit={handleSubmit}
 6         onload={handleLoad}
 7         onsuccess={handleSuccess}
 8         onerror={handleError}
 9         >
10         <lightning-messages></lightning-messages>
11         <lightning-input-field field-name="Name"></lightning-input-field>
12         <lightning-input-field field-name="Industry"></lightning-input-field>
13         <lightning-input-field field-name="AnnualRevenue"></lightning-input-field>
14         <div class="slds-m-top_medium">
15             <lightning-button class="slds-m-top_small" label="Cancel" onclick={handleReset}></lightning-button>
16             <lightning-button class="slds-m-top_small" type="submit" label="Save Record"></lightning-button>
17         </div>
18     </lightning-record-edit-form>
19 </template>

recordEditFormSample.js

 1 /* eslint-disable no-console */
 2 import { LightningElement, api } from 'lwc';
 3 import { ShowToastEvent } from 'lightning/platformShowToastEvent';
 4 export default class RecordEditFormSample extends LightningElement {
 5 
 6     @api recordId;
 7     @api objectApiName;
 8 
 9     handleSubmit(event) {
10         event.preventDefault();       // stop the form from submitting
11         const fields = event.detail.fields;
12         if(fields.Industry === null || fields.Industry === '') {
13             const evt = new ShowToastEvent({
14                 title: "Account Operated Failed",
15                 message: "Account Industry cannot be blank",
16                 variant: "error",
17                 mode:"pester"
18             });
19             this.dispatchEvent(evt);
20             return;
21         }
22         this.template.querySelector('lightning-record-edit-form').submit(fields);
23     }
24 
25     handleLoad(event) {
26         console.log('execute load');
27     }
28 
29     handleSuccess(event) {
30         const evt = new ShowToastEvent({
31             title: "Account Operated Success",
32             message: "Record is :" + event.detail.id,
33             variant: "success"
34         });
35         this.dispatchEvent(evt);
36     }
37 
38     handleError(event) {
39         const evt = new ShowToastEvent({
40             title: "Account Operated Failed",
41             message: event.detail.message,
42             variant: "error",
43             mode: "sticky"
44         });
45         this.dispatchEvent(evt);
46     }
47 
48     handleReset(event) {
49         const inputFields = this.template.querySelectorAll(
50             'lightning-input-field'
51         );
52         if (inputFields) {
53             inputFields.forEach(field => {
54                 field.reset();
55             });
56         }
57      }
58 }

Show results:

 sticky style, just click on the Close button to disappear toast.

 

 Summary: Cipian main talking Navigation and Toast relevant knowledge, which can, depending on the type Navigation and attribute the jump and do different functions such as downloading operation, articles exemplified relatively small, interested can learn in depth . There are articles in the wrong place welcome that, do not understand the welcome message.

Guess you like

Origin www.cnblogs.com/zero-zyq/p/11505295.html