salesforce lightning零基础学习(八) Aura Js 浅谈一: Component篇

 我们在开发lightning的时候,常常会在controller.js中写 component.get('v.label'), component.set('v.label','xxValue');

小伙伴肯定有疑问这些方法是怎么定义的,lightning到底有多少已经声明的方法可供我们使用,此篇主要讲述aura framework为我们提供的 component的js的主要方法。

本人salesforce环境切换到lightning,URL为:https://zero-zhang-dev-ed.lightning.force.com。

每个人的URL不同,URL 保留到force.com,然后添加一下URL: /auradocs/reference.app 即可看到aura的文档,aura文档里面给我们提供了aura framework 所有的支持的标签的描述以及使用,js的描述以及使用等等。此篇我们只是对 component的js进行说明,其他感兴趣的可以自行查看。

 点击JavaScript API, 切换到 Component,可以查看到 Aura提供的所有的方法,常用的部分方法描述如下:

 

1. set (String key, Object value):此方法最为常见了,对 attribute 设置值的引用。

eg: component.set("v.testAttribute","hello lightning") : 此赋值逻辑代表 对 testAttribute 这个attribute 赋值,内容为“hello lightning”; 此方法通常用于对attribute赋值,这里不多做举例;

2.get(String key):此方法也是最为常见的,使用属性语法返回引用的值。通常有两种用法:

  1)component.get("v.testAttribute"): 此逻辑代表获取当前component中attribute名称为testAttribute的值;

  2)componnet.get("c.testAction"): 此逻辑代表获取后台apex controller中的 testAction方法,用于和后台交互操作;

3.find(String Object name):此方法用于通过local id 获取到指定的 component。我们知道lightning每个元素都默认有一个属性:aura:id, 此属性用来标记这个组件元素的local id,理论上local id是唯一的,但是实际操作中可以不唯一,所以find这个方法返回值可以有多种形式,如果 component中针对所查的local id有不止一个,则返回一个数组来盛接,如果有一个,则直接返回当前元素,如果不存在,则直接返回undefined;

 eg: component.find("helloWorld"): 此逻辑代表获取 component 中local id为helloWorld的组件元素,如果不存在则返回undefined;

4.getLocalId(): 此方法用于获取组件元素的local id, 此方法通常用于通过事件获取事件的元素组件以后,获取元素组件的local id;

eg: TestComponent.cmp

复制代码
<aura:component>    <lightning:button id="Global_Id" aura:id="Local_Id" label="Get Local Id"                        onclick="{!c.getLocalId}"/></aura:component>
复制代码

Controller.js 端

复制代码
({     getLocalId : function(component, event, helper) {         var button = event.getSource();         console.log(button.getLocalId());     } })
复制代码

5. getGlobalId(): 此方法用于获取组件元素的global id, 此方法通常用于事件获取事件元素组件以后,获取元素组件的global id;

eg:

将上面的方法改成 getGlobalId即可;

复制代码
({     getGlobalId : function(component, event, helper) {         var button = event.getSource();         console.log(button.getGlobalId());     } })
复制代码

 6.getName():此方法用来获取当前的组件元素的名称。例如上面的TestComponent.cmp, 当我们在getGlobalId 增加 console.log(component.getName());时会打印出TestComponent;

 7.getEvent(String eventName):通过component中注册的事件名称获取事件的实例化对象;

我们假设 component 中注册了一个事件 testEvent , 它对应了一个handler名字为 testHandler,当我们点击某个button时,会触发后台的方法,此方法用于获取到事件对象并触发此事件,执行此事件对应的handler;

复制代码
testButtonHandler : function(component,event,helper) {     
                        
关键字:
50000+
5万行代码练就真实本领
17年
创办于2008年老牌培训机构
1000+
合作企业
98%
就业率

联系我们

电话咨询

0532-85025005

扫码添加微信