LOGO

How child components communicate with higher layer components

Edit

usage

The child component dispatches messages to the upper layer of the component tree via the dispatch method.

1
2
3
4
5
6
7
8
9
10
11
12
13
class Son extends san.Component {
static template = `
<div>
<button on-click='onClick'>pass up</button>
</div>
`;

onClick() {
const value = this.data.get('value');
// Distribute messages to the upper level of the component tree
this.dispatch('son-clicked', value);
}
};

The message will be passed up the component tree until it encounters the first component that processes the message. Use messages to declare the message the component will process. messages is an object, the key is the name of a message, and value is the processing function of a message, which receives an object parameter containing target (the component that dispatches the message) and value(the value of the message).

1
2
3
4
5
6
7
8
9
10
11
12
13
class GrandParent extends san.Component {
static template = '<div><slot></slot></div>';

// Declare messages that the component will process
static messages = {
'son-clicked': function (arg) {
// arg.target can get the component dispatched by the message
// arg.value can get the value of the message
this.data.set('value', arg.value);

}
}
};

examples

See the Pen higher-communication by Swan (@jiangjiu8357) on CodePen.