5.5 KiB
Executable File
5.5 KiB
Executable File
title, description, type, group, menuName, icon, order
| title | description | type | group | menuName | icon | order |
|---|---|---|---|---|---|---|
| iFrame | 0 | ⚙ 组件 | iFrame | 51 |
基本使用
内嵌外部站点,可用 iframe 来实现。
{
"type": "iframe",
"src": "https://github.com/baidu/amis",
"height": 300
}
src 使用动态数据
数据域变量
1.1.6
{
"type": "page",
"data": {
"iframeSrc": "https://github.com/baidu/amis"
},
"body": {
"type": "iframe",
"src": "${iframeSrc}",
"height": 300
}
}
其它原生 iframe 属性
2.1.0 及以上版本
还支持以下原生 iframe 属性,具体配置项请参考。
- name
- allow
- sandbox
- referrerpolicy
支持 base64 格式
2.4.0 及以上版本
src属性支持传入符合 base64 编码标准的 MIME 类型字符串,具体效果参考示例
如何和 iframe 通信
amis 向 iframe 通信
在 iframe 页面中添加message事件监听器,在 iframe 初始化、更新或者接收到其他组件发送数据的时候,会通过 postMessage 发送当前数据域数据,iframe 页面的事件监听器中可以通过e.data进行获取:
window.addEventListener('message', e => {
// e.data 获取当前数据域数据,进行使用
});
e.data 格式及参数说明:
{
"type": "amis:init", // 当前事件类型
"data": {
//... 当前数据域数据
}
}
- type: 当前事件类型
- amis:init:初始化的时候触发
- amis:update:组件更新时触发
- amis:receive:组件通过 target 接收到其他组件发送来数据的时候
- data:当前数据源数据
如果是 webpack 开发环境,注意过滤掉
webpackOk类型消息
iframe 页面向 amis 通信
可以通过以下两种方式实现 iframe 页面向 amis 通信:
注意:如果同时配置了 events 和 onEvent,amis 都会执行,且 onEvent 配置的动作行为会先于 events 执行。
步骤如下:
- 在 iframe 页面中定义消息名称和需要传递的数据。获取父级 window,并使用
postMessage传递数据,格式如下,:
window.parent.postMessage(
{
type: 'amis:detail',
data: {
iframeId: '111'
}
},
'*'
);
message格式:
type: 标识要触发的 amis 行为,请使用amis:xxx的格式,这里我们设置为配置好的detail事件data: 传给 amis 的数据,amis 会将该数据与当前数据域进行合并进行使用
- 在 amis 的 iframe 组件中指明需要监听的消息名称,以及需要执行的动作。
// 方式一:即在 amis 的 iframe 配置项中配置 events 对象
{
"type": "iframe",
"src": "http://www.xxx.com",
"events": {
"detail": {
"actionType": "dialog", // 弹窗动作
"dialog": {
"title": "弹框",
"body": "iframe 传给 amis 的 id 是:${iframeId}" // 在弹框中渲染`"iframe 传给 amis 的 id 是:${iframeId}"`这段模板,即111
}
}
}
}
// 方式二:即在 amis 的 iframe 配置项中配置 onEvent 对象
{
"type": "iframe",
"src": "http://www.xxx.com",
"onEvent": {
"detail": {
"actions": [
// 动作 1,弹窗动作
{
"actionType": "dialog",
"dialog": {
"title": "弹框",
"body": "iframe 传给 amis 的 id 是:${iframeId}" // 在弹框中渲染`"iframe 传给 amis 的 id 是:${iframeId}"`这段模板,即111
}
},
// 动作 2,触发指定组件的特性动作
{
"actionType": "crud",
"componentId": "form01",
"data": {
"iframeId": "${iframeId}" // 刷新请求参数为`"iframe 传给 amis 的 id 是:${iframeId}"`这段模板,即111
}
}
]
}
}
}
设置高度自适应
默认 amis 中只支持给 iframe 配置固定高度,我们可以通过上面说到的通信机制实现高度自适应。
- 首先在 iframe 页面中获取到页面高度
- 通过
amis:resize事件,将高度信息发送给 amis
window.parent.postMessage(
{
type: 'amis:resize',
data: {
height: 400
}
},
'*'
);
这样就可以动态设置 iframe 组件高度
属性表
| 属性名 | 类型 | 默认值 | 说明 |
|---|---|---|---|
| type | string |
"iframe" |
指定为 iFrame 渲染器 |
| className | string |
iFrame 的类名 | |
| frameBorder | Array |
frameBorder | |
| style | object |
样式对象 | |
| src | string |
iframe 地址 | |
| allow | string |
allow 配置 | |
| sandbox | string |
sandbox 配置 | |
| referrerpolicy | string |
referrerpolicy 配置 | |
| height | number或string |
"100%" |
iframe 高度 |
| width | number或string |
"100%" |
iframe 宽度 |