neutromelabs / magento2-ssr-graphql
允许在渲染时预加载 GraphQL 查询
0.1.1
2024-07-20 15:04 UTC
Requires
- magento/framework: *
- magento/module-graph-ql: *
This package is not auto-updated.
Last update: 2024-09-28 19:31:22 UTC
README
There should not be one to choose between PHP and GraphQL.
Revolutionize your customer's experience with the best from both.
Magento 2 SSR GraphQL 模块
为任何 Magento 2 前端添加 SSR GraphQL 解析功能。与任何主题兼容。与 AlpineJS 协作最佳。
概述
想法是编写一个正常的 GraphQL query
(将通过 JS 在前端使用),并在页面渲染时自动预加载它的 response
,为 JS 代码提供即时的 data
/errors
- 而不执行“第一个”Ajax 请求。
然后,JS 应该像往常一样运行,同时访问到 query
字符串、ssr
数据(变量、响应)和简化的 fetch()
,以重复查询,可选地传递新参数。
使用位置
在你的页面上的任何位置,当需要客户在页面渲染时(PHP)获得相同的[通过 GraphQL 可用]内容,而以后可以更新(JS)时。
典型用例
- 分页/懒加载 - 页面渲染时可以预加载第一组项目,然后使用相同的 GraphQL
query
和不同的variables
进行分页 - 双重检查 - 如果产品可售,则渲染“添加到购物车”按钮,并在点击时刷新相同的查询,以防止库存竞争
如何使用
简单示例 - 基于GraphQL的分页产品列表。
- 视图必须调用
makeSsrGqlCall(query, variables)
方法,从NeutromeLabs\SsrGraphql\ViewModel\SsrGraphqlViewModel
视图模型,该方法返回代表object
的 JS 片段字符串,以插入到页面 HTML 脚本标签中。
var ssrGqlExampleObject = <?= $gql->makeSsrGqlCall(<<<GRAPHQL
query productsQuery(\$currentPage: Int!) {
products (search: "", pageSize: 3, currentPage: \$currentPage) {
items {
sku
}
}
}
GRAPHQL, ['currentPage' => 1]) ?>;
renderData(); // some logic to present ssrGqlExampleObject to the customer
- 在渲染此页面时,Magento 将解析传递的查询并提供带有特殊 SSR GraphQL
object
的ssrGqlExampleObject
JS 变量。
{
// indicates, if the response is SSR-generated. true, if no "refresh" calls were made
fresh: boolean,
// "current" response data
data?: object,
// "current" response errors
errors?: object[],
ssr: {
query: string, // GraphQL query string
variables: object, // GraphQL variables, passed at the step 1
response: object, // SSR GraphQL response
},
// fetches the same query with the merged variables from the ssr.variables and parameter
fetch: (variables?: object) => Promise<object>,
// fetch(), then update the inner data and errors fields with the new response
refresh: (variables?: object) => Promise<void>,
}
- 来自 JS 变量的数据可以在页面加载后立即呈现给客户,屏幕上没有任何“加载器”。然后可以更新这些数据,而无需再次重复相同的 GraphQL 查询。
currentPage++;
ssrGqlExampleObject.refresh({
currentPage: currentPage
}).then(() => {
renderData();
})
请参阅完整的示例 https://your-magento-instance.test/ssrgql/example
,以及 src/SsrGraphql/view/frontend/templates/example/1.phtml