14

SharePoint Online SPFx Web部件绑定数据

 3 years ago
source link: https://www.cnblogs.com/jianyus/p/12955068.html
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.

SharePoint Online SPFx Web部件绑定数据

  前言

  在上一篇文章里,我们为大家介绍了如何创建SPFx Web部件,但是没有说如何获取SharePoint 网站数据。这篇文章,我们就为大家演示,如何利用列表数据模型和SharePoint SPFx模块,读取SharePoint 网站数据并展示出来。

  正文

  1.提前创建好数据列表,如下图:

 

256729-20200525094015146-1344882975.png

  2.用Visual Studio Code打开Web部件文件,如下图:

 

256729-20200525094035386-2033166213.png

  3.在头部定义列表模型,如下图:

export interface ISPLists {
  value: ISPList[];
}
export interface ISPList { Title: string; Id: string; }

  4.添加执行REST API请求的帮助程序类 spHttpClient

import {
  SPHttpClient,
  SPHttpClientResponse
} from '@microsoft/sp-http';

  5.添加列表模型和帮助程序类位置,如下图:

 

256729-20200525094150491-1231261674.png

  6.添加请求数据的方法,调用REST服务获取数据,方法如下:

private _getListData(): Promise<ISPLists> {
  return this.context.spHttpClient.get(this.context.pageContext.web.absoluteUrl + `/_api/web/lists/getbytitle('MyList')/items`, SPHttpClient.configurations.v1)
    .then((response: SPHttpClientResponse) => {
      return response.json();
    });
}

  7.添加渲染数据的方法,渲染成我们需要展示的格式,方法如下:

private _renderList(items: ISPList[]): void {
  let html: string = '';

  items.forEach((item: ISPList) => {
    html += `<div>${item.Title}</div>`;
  });

  const listContainer: Element = this.domElement.querySelector('#MyContainer');
  listContainer.innerHTML = html;
}

  8.修改渲染Web部件的方法,将获取的数据渲染到Web部件,方法如下:

public render(): void {
  this.domElement.innerHTML = `<div id="MyContainer" />`;

  this._getListData()
    .then((response) => {
      this._renderList(response.value);
    });
}

  9.添加方法的位置,如下图:

 

256729-20200525094213332-210455454.png

  10.在SharePoint Online站点中测试SPFx Web部件,如下图:

 

256729-20200525094227277-504111603.png

  结束语

  至此,我们看到SPFx Web部件,已经获取到了SharePoint Online站点中的列表数据。之后,我们就可以把部件部署到网站中,使用了。


About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK