feature: Add inject(key, value) as 2nd argument of plugins

This commit is contained in:
Sébastien Chopin 2017-08-24 20:38:28 +02:00
parent 42f2a59fd2
commit e32a3755dd

View File

@ -50,7 +50,7 @@ async function createApp (ssrContext) {
// making them available everywhere as `this.$router` and `this.$store`.
const app = {
router,
<% if(store) { %> store,<% } %>
<% if (store) { %> store,<% } %>
_nuxt: {
defaultTransition,
transitions: [ defaultTransition ],
@ -101,17 +101,42 @@ async function createApp (ssrContext) {
route,
next,
error: app._nuxt.error.bind(app),
<% if(store) { %>store,<% } %>
<% if (store) { %>store,<% } %>
req: ssrContext ? ssrContext.req : undefined,
res: ssrContext ? ssrContext.res : undefined,
beforeRenderFns: ssrContext ? ssrContext.beforeRenderFns : undefined
}, app)
const inject = function (key, value) {
if (!key) throw new Error('inject(key, value) has no key provided')
if (!value) throw new Error('inject(key, value) has no value provided')
key = '$' + key
// Add into app
app[key] = value
// Add into vm
Vue.use(() => {
const installKey = '__nuxt_' + key + '_installed__'
if (Vue[installKey]) return
Vue[installKey] = true
if (!Vue.prototype.hasOwnProperty(key)) {
Object.defineProperty(Vue.prototype, key, {
get () {
return this.$root.$options[key]
}
})
}
})
<% if (store) { %>
// Add into store
store[key] = app[key]
<% } %>
}
<% plugins.filter(p => p.ssr).forEach(plugin => { %>
if (typeof <%= plugin.name %> === 'function') await <%= plugin.name %>(ctx)<% }) %>
if (typeof <%= plugin.name %> === 'function') await <%= plugin.name %>(ctx, inject)<% }) %>
<% if (plugins.filter(p => !p.ssr).length) { %>
if (process.browser) { <% plugins.filter(p => !p.ssr).forEach(plugin => { %>
if (typeof <%= plugin.name %> === 'function') await <%= plugin.name %>(ctx)<% }) %>
if (typeof <%= plugin.name %> === 'function') await <%= plugin.name %>(ctx, inject)<% }) %>
}<% } %>
<% if (store) { %>