LOGO

How to Update Child Components?

Edit

props

Pass parent data to a child component with props, the child component will automatically get updated upon data changes.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
class Son extends san.Component {
static template = `
<div>
<p>Son's name: {{firstName}}</p>
</div>
`;
};

class Parent extends san.Component {
static template = `
<div>
<input value="{= firstName =}" placeholder="please input">
<ui-son firstName="{{firstName}}"/>
</div>
`;

static components = {
'ui-son': Son
};

initData() {
return {
firstName: 'trump'
}
}
};

See the Pen san-parent-to-child-prop by liuchaofan (@asd123freedom) on CodePen.

ref

Actually the reference to the child component can be obtained by the .ref() method. Having this reference, we can call ref.data.set() or its member methods to update the child component’s data.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
class Son extends san.Component {
static template = `
<div>
<p>Son's: {{firstName}}</p>
</div>
`;
};

class Parent extends san.Component {
static template = `
<div>
<input value="{= firstName =}" placeholder="please input">
<button on-click='onClick'>Pass to the Child</button>
<ui-son san-ref="son"/>
</div>
`;
static components = {
'ui-son': Son
};
onClick() {
this.ref('son').data.set('firstName', this.data.get('firstName'));
}
}

See the Pen san-parent-to-child-ref by liuchaofan (@asd123freedom) on CodePen.

message

Apart from the .ref() method, child component’s reference can also be found in the event object which is dispatched from the child.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
class Son extends san.Component {
static template = `
<div>
<p>Son's name: {{firstName}}</p>
<button on-click='onClick'>I want a name</button>
</div>
`;

onClick() {
this.dispatch('son-clicked');
}
};

class Parent extends san.Component {
static template = `
<div>
<input value="{= firstName =}" placeholder="please input">
<ui-son/>
</div>
`;

// declare the expected message names
static messages = {
'son-clicked': function (arg) {
let son = arg.target;
let firstName = this.data.get('firstName');
son.data.set('firstName', firstName);
}
};

static components = {
'ui-son': Son
};

initData() {
return {
firstName: 'trump'
}
}
};

See the Pen san-parent-to-child-prop by liuchaofan (@asd123freedom) on CodePen.