單頁應用程式 (SPA) 可為網站使用者提供引人入勝的體驗。開發人員希望能夠使用SPA架構建立網站,而作者則希望能夠順暢地編輯使用SPA架構建立之網站的AEM內容。
SPA製作功能提供全方位的解決方案,可支援AEM中的SPA。 本文介紹如何改寫簡單的現有React元件以與AEM SPA編輯器搭配使用的範例。
SPA編輯器是建議解決方案,適用於需要SPA架構使用者端轉譯的專案(例如React或Angular)。
有了AEM所需的簡單且輕量型的合約,以及SPA與SPA編輯器之間的建立合約,直接了當要採用現有的Javascript應用程式,並將其調整為與AEM中的SPA搭配使用時,就很簡單了。
本文說明We.Retail Journal範例SPA上的天氣元件範例。
您應熟悉 適用於AEM的SPA應用程式結構 閱讀本文之前。
本檔案使用 We.Retail日誌應用程式 僅供展示之用。 它不應用於任何專案。
任何 AEM 專案都應利用 AEM 專案原型,它支援使用 React 或 Angular 的 SPA 專案並利用 SPA SDK。
氣象元件可在We.Retail Journal應用程式的左上角找到。 它會顯示定義位置的目前氣象,以動態方式提取天氣資料。
在SPA編輯器中編寫SPA的內容時,天氣元件會以任何其他AEM元件的形式出現、使用工具列完成並可編輯。
城市可在對話方塊中更新,就像任何其他AEM元件一樣。
此變更會持續存在,而元件會自動以新天氣資料更新。
天氣元件實際上是根據公開可用的React元件,稱為 React Open Weather,此元件已改編為We.Retail Journal範例SPA應用程式中的元件。
以下是使用React Open Weather元件的NPM檔案片段。
檢閱自訂天氣元件的程式碼( Weather.js
)在We.Retail日誌應用程式中:
第16行:React Open Weather Widget會視需要載入。
第46行:此 MapTo
函式將此React元件與對應的AEM元件建立關聯,以便在SPA編輯器中編輯它。
第22-29行:此 EditConfig
會定義,檢查是否已填入城市,如果為空,則會定義值。
第31-44行:天氣元件會延伸 Component
類別,並根據NPM使用檔案中的定義,為React Open Weather元件提供必要資料,以及呈現元件。
/*~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
~ Copyright 2018 Adobe Systems Incorporated
~
~ Licensed under the Apache License, Version 2.0 (the "License");
~ you may not use this file except in compliance with the License.
~ You may obtain a copy of the License at
~
~ https://www.apache.org/licenses/LICENSE-2.0
~
~ Unless required by applicable law or agreed to in writing, software
~ distributed under the License is distributed on an "AS IS" BASIS,
~ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
~ See the License for the specific language governing permissions and
~ limitations under the License.
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~*/
import React, {Component} from 'react';
import ReactWeather from 'react-open-weather';
import {MapTo} from '@adobe/aem-react-editable-components';
require('./Weather.css');
const WeatherEditConfig = {
emptyLabel: 'Weather',
isEmpty: function() {
return !this.props || !this.props.cq_model || !this.props.cq_model.city || this.props.cq_model.city.trim().length < 1;
}
};
class Weather extends Component {
render() {
let apiKey = "12345678901234567890";
let city;
if (this.props.cq_model) {
city = this.props.cq_model.city;
return <ReactWeather key={'react-weather' + Date.now()} forecast="today" apikey={apiKey} type="city" city={city} />
}
return null;
}
}
MapTo('we-retail-journal/global/components/weather')(Weather, WeatherEditConfig);
雖然後端元件必須已存在,但前端開發人員可以在We.Retail Journal SPA中善用React Open Weather元件,且只需很少的程式碼。
如需針對AEM開發SPA的詳細資訊,請參閱文章 針對AEM開發SPA.