baidu/san-composition

数据的可复用性问题

Closed this issue · 1 comments

在 san-composition 的实现可复用部分的文档看到这个例子:

// 功能 1
export const useContactList = () => {
    // focus next line
    const contactList = data('contactList', []);
    method('getContactList', () => {
        // ...
        contactList.set([/* ... */]);
    });
    onAttached(function () { this.getContactList(); });
};

// 功能 2
export const useFavoriteList = () => {
    // focus next line
    const favoriteList = data('favoriteList', []);
    method('getFavoriteList', () => {
        // ...
        favoriteList.set([/* ... */]);
    });
    onAttached(function () { this.getFavoriteList(); });
};

关于 data 这部分有两个问题:

  1. data 是否可以从别的地方获取并初始化,而不是在复用单元内部初始化。因为不同的复用单元可能会使用到相同的数据
  2. 数据变量是否可以重命名,方便使用不同名变量的组件复用相同的一段逻辑

你好,
1.data 是可以从别的地方获取,不一定要写在一个复用单元里面,这里写在一起是按业务逻辑组织代码的思路;
2.把数据变量的 key 通过参数传过去?

export const useContactList = ({contactList = 'contactList', getContactList = 'getContactList'}) => {
    // focus next line
    const contactList = data(contactList, []);
    method(getContactList, () => {
        // ...
        contactList.set([/* ... */]);
    });
    onAttached(function () { this.getContactList(); });
};