• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1# PluginComponent
2
3提供外部应用组件嵌入式显示功能,即外部应用提供的UI可在本应用内显示。如需通过跨进程通信实现更新,请参考[@ohos.pluginComponent](../apis/js-apis-plugincomponent.md)。
4
5
6>  **说明:**
7>
8>  - 该组件从API Version 9开始支持。后续版本如有新增内容,则采用上角标单独标记该内容的起始版本。
9>  - 本组件为系统接口。
10
11## 子组件
12
1314
15
16## 接口
17
18PluginComponent(value: { template: PluginComponentTemplate, data: KVObject})
19
20创建插件组件,用于显示外部应用提供的UI。
21
22**参数:**
23
24| 参数名 | 参数类型                                                                                                                                                        | 必填 | 参数描述                                                                                                  |
25| ------ | --------------------------------------------------------------------------------------------------------------------------------------------------------------- | ---- | --------------------------------------------------------------------------------------------------------- |
26| value  | {<br/>template:&nbsp; [PluginComponentTemplate](#plugincomponenttemplate类型说明),<br/>data:&nbsp;[KVObject](../apis/js-apis-plugincomponent.md#kvobject)<br/>} | 是   | template:&nbsp;&nbsp;组件模板,用于跟提供者定义的组件绑定。<br/>data:&nbsp;传给插件组件提供者使用的数据。 |
27
28## PluginComponentTemplate类型说明
29
30| 参数       | 类型   | 描述                        |
31| ---------- | ------ | --------------------------- |
32| source     | string | 组件模板名。                |
33| bundleName | string | 提供者Ability的bundleName。 |
34## 属性
35支持[通用属性size](ts-universal-attributes-size.md),且必须设置size。
36
37**说明:**
38
39  模板支持两种提供方式:
40* 1.使用绝对路径进行资源提供:source字段填写模板绝对路径,bundleName不需要填写。仅适用于不需要加载资源的单独模板页面,不建议使用。
41* 2.通过应用包进行资源提供:bundleName字段需要填写应用包名;source字段填写相对hap包的模板相对路径,对于多hap场景,通过相对路径&hap名称的方式进行hap包的确认。
42
43  例如:{source:'ets/pages/plugin.js&plugin', bundleName:'com.example.provider'}
44
45  仅对FA模型支持source字段填写AbilityName进行模板提供。
46
47  例如:{source:'plugin', bundleName:'com.example.provider'}
48
49
50## 事件
51
52仅支持[手势事件](ts-gesture-settings.md)分发给提供方页面,并在提供方页面内部处理。
53
54除支持[通用事件](ts-universal-events-click.md),还支持以下事件:
55
56| 名称                                                                                                                | 功能描述                                                               |
57| ------------------------------------------------------------------------------------------------------------------- | ---------------------------------------------------------------------- |
58| onComplete(callback:&nbsp;()&nbsp;=&gt;&nbsp;void)                                                                  | 组件加载完成回调。                                                     |
59| onError(callback:&nbsp;(info:&nbsp;{&nbsp;errcode:&nbsp;number,&nbsp;msg:&nbsp;string&nbsp;})&nbsp;=&gt;&nbsp;void) | 组件加载错误回调。<br/>errcode:&nbsp;错误码。<br/>msg:&nbsp;错误信息。 |
60
61## 示例
62
63
64### 组件使用方
65
66```ts
67//PluginUserExample.ets
68import plugin from "./plugin_component"
69class source2BundleName {
70  source: string = ""
71  bundleName: string = ""
72}
73interface Info{
74  errcode:number,
75  msg:string
76}
77@Entry
78@Component
79struct PluginUserExample {
80  @StorageLink("plugincount") plugincount: Object[] = [
81    { source: 'plugincomponent1', bundleName: 'com.example.plugin' } as source2BundleName,
82    { source: 'plugintemplate', bundleName: 'com.example.myapplication' } as source2BundleName,
83    { source: 'plugintemplate', bundleName: 'com.example.myapplication' } as source2BundleName]
84
85  build() {
86    Flex({ direction: FlexDirection.Column, alignItems: ItemAlign.Center, justifyContent: FlexAlign.Center }) {
87      Text('Hello World')
88        .fontSize(50)
89        .fontWeight(FontWeight.Bold)
90      Button('Register Request Listener')
91        .fontSize(30)
92        .width(400)
93        .height(100)
94        .margin({top:20})
95        .onClick(()=>{
96          plugin.onListener()
97          console.log("Button('Register Request Listener')")
98        })
99      Button('Request')
100        .fontSize(50)
101        .width(400)
102        .height(100)
103        .margin({ top: 20 })
104        .onClick(() => {
105          plugin.Request()
106          console.log("Button('Request')")
107        })
108      ForEach(this.plugincount, (item: source2BundleName) => {
109        PluginComponent({
110          template: { source: 'PluginProviderExample', bundleName: 'com.example.plugin' },
111          data: { 'countDownStartValue': 'new countDownStartValue' }
112        }).size({ width: 500, height: 100 })
113          .onComplete(() => {
114            console.log("onComplete")
115          })
116          .onError((info:Info) => {
117            console.log("onComplete" + info.errcode + ":" + info.msg)
118          })
119      })
120    }
121    .width('100%')
122    .height('100%')
123  }
124}
125```
126
127### 组件提供方
128
129```ts
130//PluginProviderExample.ets
131import plugin from "./plugin_component"
132
133@Entry
134@Component
135struct PluginProviderExample {
136  @State message: string = 'no click!'
137
138  build() {
139    Flex({ direction: FlexDirection.Column, alignItems: ItemAlign.Center, justifyContent: FlexAlign.Center }) {
140      Button('Register Push Listener')
141        .fontSize(30)
142        .width(400)
143        .height(100)
144        .margin({top:20})
145        .onClick(()=>{
146          plugin.onListener()
147          console.log("Button('Register Push Listener')")
148        })
149      Button('Push')
150        .fontSize(30)
151        .width(400)
152        .height(100)
153        .margin({top:20})
154        .onClick(()=>{
155          plugin.Push()
156          this.message = "Button('Push')"
157          console.log("Button('Push')")
158        })
159      Text(this.message)
160        .height(150)
161        .fontSize(30)
162        .padding(5)
163        .margin(5)
164    }.width('100%').height('100%').backgroundColor(0xDCDCDC).padding({ top: 5 })
165  }
166}
167```
168
169### Plugin组件工具
170
171#### FA模型
172```js
173//当前示例代码仅适用于js源文件
174//plugin_component.js
175import pluginComponentManager from '@ohos.pluginComponent'
176
177function onPushListener(source, template, data, extraData) {
178  console.log("onPushListener template.source=" + template.source)
179  var jsonObject = JSON.parse(data.componentTemplate.source)
180  console.log("request_callback1:source json object" + jsonObject)
181  var jsonArry = jsonObject.ExternalComponent
182  for (var i in jsonArry) {
183    console.log(jsonArry[i])
184  }
185  console.log("onPushListener:source json object" + jsonObject)
186  console.log("onPushListener:source json string" + JSON.stringify(jsonObject))
187  console.log("onPushListener template.ability=" + template.ability)
188  console.log("onPushListener data=" + JSON.stringify(data))
189  console.log("onPushListener extraData=" + JSON.stringify(extraData))
190}
191
192function onRequestListener(source, name, data)
193{
194    console.log("onRequestListener name=" + name);
195    console.log("onRequestListener data=" + JSON.stringify(data));
196    return {template:"plugintemplate", data:data};
197}
198
199export default {
200  //register listener
201  onListener() {
202    pluginComponentManager.on("push", onPushListener)
203    pluginComponentManager.on("request", onRequestListener)
204  },
205  Push() {
206    // 组件提供方主动发送事件
207    pluginComponentManager.push(
208      {
209        want: {
210          bundleName: "com.example.plugin",
211          abilityName: "com.example.myapplication.PluginProviderExample",
212        },
213        name: "PluginProviderExample",
214        data: {
215          "key_1": "plugin component test",
216          "key_2": 34234
217        },
218        extraData: {
219          "extra_str": "this is push event"
220        },
221        jsonPath: "",
222      },
223      (err, data) => {
224        console.log("push_callback: push ok!");
225      }
226    )
227  },
228  Request() {
229    // 组件使用方主动发送事件
230    pluginComponentManager.request({
231        want: {
232          bundleName: "com.example.plugin",
233          abilityName: "com.example.myapplication.PluginProviderExample",
234        },
235        name: "PluginProviderExample",
236        data: {
237          "key_1": "plugin component test",
238          "key_2": 34234
239        },
240        jsonPath: "",
241      },
242      (err, data) => {
243        console.log("request_callback: componentTemplate.ability=" + data.componentTemplate.ability)
244        console.log("request_callback: componentTemplate.source=" + data.componentTemplate.source)
245        var jsonObject = JSON.parse(data.componentTemplate.source)
246        console.log("request_callback:source json object" + jsonObject)
247        var jsonArry = jsonObject.ExternalComponent
248        for (var i in jsonArry) {
249          console.log(jsonArry[i])
250        }
251        console.log("request_callback:source json string" + JSON.stringify(jsonObject))
252        console.log("request_callback: data=" + JSON.stringify(data.data))
253        console.log("request_callback: extraData=" + JSON.stringify(data.extraData))
254      }
255    )
256  }
257}
258```
259
260#### Stage模型
261```js
262//当前示例代码仅适用于js源文件
263//plugin_component.js
264import pluginComponentManager from '@ohos.pluginComponent'
265
266function onPushListener(source, template, data, extraData) {
267  console.log("onPushListener template.source=" + template.source)
268  var jsonObject = JSON.parse(data.componentTemplate.source)
269  console.log("request_callback1:source json object" + jsonObject)
270  var jsonArry = jsonObject.ExternalComponent
271  for (var i in jsonArry) {
272    console.log(jsonArry[i])
273  }
274  console.log("onPushListener:source json object" + jsonObject)
275  console.log("onPushListener:source json string" + JSON.stringify(jsonObject))
276  console.log("onPushListener template.ability=" + template.ability)
277  console.log("onPushListener data=" + JSON.stringify(data))
278  console.log("onPushListener extraData=" + JSON.stringify(extraData))
279}
280
281function onRequestListener(source, name, data)
282{
283    console.log("onRequestListener name=" + name);
284    console.log("onRequestListener data=" + JSON.stringify(data));
285    return {template:"plugintemplate", data:data};
286}
287
288export default {
289  //register listener
290  onListener() {
291    pluginComponentManager.on("push", onPushListener)
292    pluginComponentManager.on("request", onRequestListener)
293  },
294  Push() {
295    // 组件提供方主动发送事件
296    pluginComponentManager.push(
297      {
298        owner: {
299          bundleName: "com.example.myapplication",
300          abilityName: "com.example.myapplication.MainAbility",
301        },
302        target: {
303          bundleName: "com.example.plugin",
304          abilityName: "com.example.myapplication.PluginProviderExample",
305        },
306        name: "PluginProviderExample",
307        data: {
308          "key_1": "plugin component test",
309          "key_2": 34234
310        },
311        extraData: {
312          "extra_str": "this is push event"
313        },
314        jsonPath: "",
315      },
316      (err, data) => {
317        console.log("push_callback: push ok!");
318      }
319    )
320  },
321  Request() {
322    // 组件使用方主动发送事件
323    pluginComponentManager.request({
324        owner: {
325          bundleName: "com.example.myapplication",
326          abilityName: "com.example.myapplication.MainAbility",
327        },
328        target: {
329          bundleName: "com.example.plugin",
330          abilityName: "com.example.myapplication.PluginProviderExample",
331        },
332        name: "PluginProviderExample",
333        data: {
334          "key_1": "plugin component test",
335          "key_2": 34234
336        },
337        jsonPath: "",
338      },
339      (err, data) => {
340        console.log("request_callback: componentTemplate.ability=" + data.componentTemplate.ability)
341        console.log("request_callback: componentTemplate.source=" + data.componentTemplate.source)
342        var jsonObject = JSON.parse(data.componentTemplate.source)
343        console.log("request_callback:source json object" + jsonObject)
344        var jsonArry = jsonObject.ExternalComponent
345        for (var i in jsonArry) {
346          console.log(jsonArry[i])
347        }
348        console.log("request_callback:source json string" + JSON.stringify(jsonObject))
349        console.log("request_callback: data=" + JSON.stringify(data.data))
350        console.log("request_callback: extraData=" + JSON.stringify(data.extraData))
351      }
352    )
353  }
354}
355```
356