props

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

  1. class Son extends san.Component {
  2. static template = `
  3. <div>
  4. <p>Son's name: {{firstName}}</p>
  5. </div>
  6. `;
  7. };
  8. class Parent extends san.Component {
  9. static template = `
  10. <div>
  11. <input value="{= firstName =}" placeholder="please input">
  12. <ui-son firstName="{{firstName}}"/>
  13. </div>
  14. `;
  15. static components = {
  16. 'ui-son': Son
  17. };
  18. initData() {
  19. return {
  20. firstName: 'trump'
  21. }
  22. }
  23. };

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

ref

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

  1. class Son extends san.Component {
  2. static template = `
  3. <div>
  4. <p>Son's: {{firstName}}</p>
  5. </div>
  6. `;
  7. };
  8. class Parent extends san.Component {
  9. static template = `
  10. <div>
  11. <input value="{= firstName =}" placeholder="please input">
  12. <button on-click='onClick'>传给子组件</button>
  13. <ui-son san-ref="son"/>
  14. </div>
  15. `;
  16. static components = {
  17. 'ui-son': Son
  18. };
  19. onClick() {
  20. this.ref('son').data.set('firstName', this.data.get('firstName'));
  21. }
  22. }

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

message

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

  1. class Son extends san.Component {
  2. static template = `
  3. <div>
  4. <p>Son's name: {{firstName}}</p>
  5. <button on-click='onClick'>I want a name</button>
  6. </div>
  7. `;
  8. onClick() {
  9. this.dispatch('son-clicked');
  10. }
  11. };
  12. class Parent extends san.Component {
  13. static template = `
  14. <div>
  15. <input value="{= firstName =}" placeholder="please input">
  16. <ui-son/>
  17. </div>
  18. `;
  19. // 声明组件要处理的消息
  20. static messages = {
  21. 'son-clicked': function (arg) {
  22. let son = arg.target;
  23. let firstName = this.data.get('firstName');
  24. son.data.set('firstName', firstName);
  25. }
  26. };
  27. static components = {
  28. 'ui-son': Son
  29. };
  30. initData() {
  31. return {
  32. firstName: 'trump'
  33. }
  34. }
  35. };

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