描述:
把所有UI资源封装在一个独立于index.html文件的组件Component.js中。
Component 是SAPUI5应用程序中使用的独立和可重用的部件。
现在,每当我们访问资源时,我们将相对于Component.js(而不是相对于index.html)执行此操作。这种架构上的改变使我们的应用程序可以在比静态的index.html页面更灵活的环境中使用,比如在SAP Fiori launchpad这样的容器中。
Component.js(新建)
sap.ui.define([
"sap/ui/core/UIComponent",
"sap/ui/model/json/JSONModel",
"sap/ui/model/resource/ResourceModel"
],(UIComponent,JSONModel,ResourceModel) => {
"use strict";
return UIComponent.extend("ui5.walkthrough.Component",{
metadata : {
"rootView" : {
"viewName": "ui5.walkthrough.view.App",
"type": "XML",
"async": true,
"id": "app"
}
},
init : function () {
//使得根控件能够返回rootView,若无此语句,则返回null
UIComponent.prototype.init.apply(this, arguments);
//将数据模块放入视图
const oData = {
recipient : {
name : "World"
}
};
const oModel = new JSONModel(oData);
this.setModel(oModel);
//将i18n模块放入视图
const i18nModel = new ResourceModel({
bundleName:"ui5.walkthrough.i18n.i18n"
});
this.setModel(i18nModel,"i18n");
}
});
});
App.controller.js
sap.ui.define([
"sap/ui/core/mvc/Controller",
"sap/m/MessageToast",
],(Controller,MessageToast) => {
"use strict";
return Controller.extend("ui5.walkthrough.controller.App",{
onShowHello:function(){
//从视图中读取绑定的模块资源
const oBundle = this.getView().getModel("i18n").getResourceBundle();
const sRecipient = this.getView().getModel().getProperty("/recipient/name");
const sMsg = oBundle.getText("helloMsg",[sRecipient]);
MessageToast.show(sMsg);
}
});
});
index.js
sap.ui.define([
"sap/ui/core/ComponentContainer"
],(ComponentContainer) => {
"use strict";
new ComponentContainer({
//name:包含组件的包
name: "ui5.walkthrough",
//setting:组件创建时传递给组件的设置对象
settings : {
id : "walkthrough"
},
//async:是否异步
async: true
}).placeAt("content");
});
将控制器中的init函数移到组件中,增加根视图属性以替代index.js去管理视图,index.js则根据组件配置为我们实例化视图
项目结构和文件关系
App.controller.js:存储控制器方法
读取视图资源 ↑ ↓ 响应视图调用方法处理数据
App.view.xml:管理视图控件、存储
在视图中放入模块资源 ↑ ↓ 作为组件的元数据-父视图
component.js:管理绑定视图、初始化模块资源
绑定组件↑ ↓传递视图
index.js:配置组件
全局设定 ↑ ↓ 实例化视图
index.html