Page.PageHook

12003

pageHook is a configuration option used to run certain operations before a page loads. It can be used to fetch data, perform validation, and more. pageHook supports beforeHook-type hooks.

beforeHook

beforeHook runs before the page loads. In this example, we’ll create a service named pageHookDemo.js and add a method demoPageOfBeforeHook. This method returns an object containing a content property.

  • Add /app/service/pageHookDemo.js:
  1. 'use strict';
  2. const Service = require('egg').Service;
  3. class PageHookDemoService extends Service {
  4. async demoPageOfBeforeHook() {
  5. return { content: '这是一个页面的 beforeHook demo' };
  6. }
  7. }
  8. module.exports = PageHookDemoService;
  • Modify the _page table’s pageHook:
    | pageId | pageType | pageHook |
    |--------|-----------|----------|
    | demoPage | showInMenu | {"beforeHook":[{"field": "beforeHookResult", "service": "pageHookDemo", "serviceFunc": "demoPageOfBeforeHook"}]} |

  • Finally, use the data populated by beforeHook on the page /app/view/page/demoPage.html. By using <$ beforeHookResult.content $>, you can display the content fetched by beforeHook on the page:

  1. <v-app>
  2. <h2>内容: <$ beforeHookResult.content $></h2>
  3. </v-app>
  4. <script type="module">
  5. new Vue({
  6. el: '#app',
  7. template: '#app-template',
  8. vuetify: new Vuetify(),
  9. data:{
  10. },
  11. })
  12. </script>