LWC-001_Event

文章来源: Events (lwc.dev)

1. 监控子组件的动作:

Child.html

<template>
<button>Click</button>

</template>

Parent.html


<template>

<c-child></c-child>

</template>


Parent.JS

import { LightningElement } from 'lwc';

export default class App extends LightningElement {
    renderedCallback(){
        this.template.querySelector('c-child').addEventListener('click',
         this.handleClick);
    }

    handleClick(e){
        // Your code here
        alert('This is come from p');
    }
}

2. 普通的一个Action

  <div>
    <button onclick={handlePrevious}>Previous</button>
    <button onclick={handleNext} class="right">Next</button>
  </div>


     handlePrevious() {
        this.dispatchEvent(new CustomEvent('previous'));
      alert('P')
    }

    handleNext() {
        this.dispatchEvent(new CustomEvent('next'));
            alert('N')
    }

  

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. The event type is the name of the event. You can use any string as your event type. However, we recommend that you conform with the DOM event standard.

  • No uppercase letters
  • No spaces
  • Use underscores to separate words

3. 

Child.html
<template>
  <div>
    <button onclick={handlePrevious}>Previous</button>
    <button onclick={handleNext} class="right">Next</button>
  </div>
</template>

child.js
import { LightningElement } from "lwc";

/**
 * Show an item
 */
export default class Child extends LightningElement {
 handlePrevious() {
        this.dispatchEvent(new CustomEvent('previous1'));
    }

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


parent

  4. child pass Data to Parent

参照Recipes上的例子:lwc-recipes/force-app/main/default/lwc/contactListItem at main · trailheadapps/lwc-recipes · GitHub

 lwc-recipes/eventWithData.html at main · trailheadapps/lwc-recipes · GitHub

另外实际项目上的代码

CreateFolder、FavoriteView
 
5. parent to child
 
 
6. 动态添加Option下拉选项值:
https://salesforce.stackexchange.com/questions/275530/dynamically-update-lightning-combobox-lightning-web-component 
https://developer.salesforce.com/forums/?id=9062I000000DHcLQAW 
posted @ 2022-07-22 10:37  BandariFang  阅读(42)  评论(0编辑  收藏  举报