LOGO

父组件如何更新子组件?

编辑本文

props

最简单的也是最常用的父组件更新子组件的方式就是父组件将数据通过props传给子组件,当相关的变量被更新的时候,MVVM框架会自动将数据的更新映射到视图上。

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

更灵活的方式是通过ref拿到子组件的实例,通过这个子组件的实例可以手动调用this.data.set来更新子组件的数据,或者直接调用子组件声明时定义的成员方法。

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'>传给子组件</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

除了ref外,父组件在接收子组件向上传递的消息的时候,也可以拿到子组件的实例,之后的操作方式就和上面所说的一样了。

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>
`;

// 声明组件要处理的消息
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.