mirror of
https://github.com/nuxt/nuxt.git
synced 2024-11-23 14:15:13 +00:00
hooks: Handle hooks as object
This commit is contained in:
parent
7aa0863cb7
commit
7137f848a2
@ -291,7 +291,7 @@ Options.defaults = {
|
||||
editor: {
|
||||
editor: 'code'
|
||||
},
|
||||
hooks: () => {},
|
||||
hooks: null,
|
||||
messages: {
|
||||
error_404: 'This page could not be found',
|
||||
server_error: 'Server error',
|
||||
|
@ -6,6 +6,7 @@ import Renderer from './renderer'
|
||||
import Debug from 'debug'
|
||||
import enableDestroy from 'server-destroy'
|
||||
import Module from 'module'
|
||||
import { isPlainObject } from 'lodash'
|
||||
import { join, resolve } from 'path'
|
||||
|
||||
const debug = Debug('nuxt:')
|
||||
@ -41,8 +42,10 @@ export default class Nuxt {
|
||||
return this._ready
|
||||
}
|
||||
|
||||
// Call hooks
|
||||
if (typeof this.options.hooks === 'function') {
|
||||
// Add hooks
|
||||
if (isPlainObject(this.options.hooks)) {
|
||||
this.addObjectHooks(this.options.hooks)
|
||||
} else if (typeof this.options.hooks === 'function') {
|
||||
this.options.hooks(this.hook)
|
||||
}
|
||||
// Add nuxt modules
|
||||
@ -56,6 +59,9 @@ export default class Nuxt {
|
||||
}
|
||||
|
||||
hook(name, fn) {
|
||||
if (!name || typeof fn !== 'function') {
|
||||
return
|
||||
}
|
||||
this._hooks[name] = this._hooks[name] || []
|
||||
this._hooks[name].push(fn)
|
||||
}
|
||||
@ -73,6 +79,17 @@ export default class Nuxt {
|
||||
}
|
||||
}
|
||||
|
||||
addObjectHooks(hooksObj) {
|
||||
Object.keys(hooksObj).forEach((name) => {
|
||||
let hooks = hooksObj[name]
|
||||
hooks = (Array.isArray(hooks) ? hooks : [hooks])
|
||||
|
||||
hooks.forEach((hook) => {
|
||||
this.hook(name, hook)
|
||||
})
|
||||
})
|
||||
}
|
||||
|
||||
listen(port = 3000, host = 'localhost') {
|
||||
return new Promise((resolve, reject) => {
|
||||
const server = this.renderer.app.listen({ port, host, exclusive: false }, (err) => {
|
||||
|
@ -32,6 +32,10 @@ test.before('Init Nuxt.js', async t => {
|
||||
server.listen(port)
|
||||
})
|
||||
|
||||
test('Check ready hook called', async t => {
|
||||
t.true(nuxt.__hook_called__)
|
||||
})
|
||||
|
||||
test('/stateless', async t => {
|
||||
const window = await nuxt.renderAndGetWindow(url('/stateless'))
|
||||
const html = window.document.body.innerHTML
|
||||
|
7
test/fixtures/basic/nuxt.config.js
vendored
7
test/fixtures/basic/nuxt.config.js
vendored
@ -6,5 +6,12 @@ module.exports = {
|
||||
{ route: '/users/3', payload: { id: 3000 } }
|
||||
],
|
||||
interval: 200
|
||||
},
|
||||
hooks: {
|
||||
ready(nuxt) {
|
||||
nuxt.__hook_called__ = true
|
||||
},
|
||||
bad: null,
|
||||
'': true
|
||||
}
|
||||
}
|
||||
|
Loading…
Reference in New Issue
Block a user