將記錄器注入 Nuxt 實體時我做錯了什么?
loglevel.client.js
import log from 'loglevel';
log.setLevel(process.env.LOG_LEVEL || 'debug');
export default ({ app }, inject) => {
inject('log', log);
log.debug('logger set up')
}
nuxt.config.js
plugins: [
'~/plugins/loglevel.client.js',
'~/plugins/api.js',
],
插件\api.js
if (process.client) {
console.log('on client console')
this.$log.error('on client $log')
}
瀏覽器:
api.js?e568:4 on client console
08:22:26.456 api.js?e568:5 Uncaught TypeError: Cannot read properties of undefined (reading '$log')
at eval (api.js?e568:5:1)
at Module../plugins/api.js (app.js:1033:1)
uj5u.com熱心網友回復:
inject$log通過將其作為屬性附加到根 Vue 應用程式和 Nuxt 背景關系,使其在其他地方可用。
插件在根 Vue 應用程式實體化之前運行——你不能通過 訪問$log,this.$log除非this參考根 Vue 應用程式實體(就像它在組件中所做的那樣)。
相反,您必須通過 Nuxt 背景關系進行訪問,它可以作為插件$log的第一個引數方便地使用。api.js
export default ({ $log }) => {
if (process.client) {
console.log('on client console')
$log.error('on client $log')
}
}
從檔案:
(Nuxt)背景關系提供了從 Nuxt 到 Vue 組件的其他物件/引數,并且在特殊的 nuxt 生命周期區域中可用,例如 asyncData 、 fetch 、 plugins 、 middleware 和 nuxtServerInit 。
此外,它看起來像是loglevel注冊為客戶端插件(loglevel.client.js)。該代碼不會在服務器端運行——因此您不必在process.client.
轉載請註明出處,本文鏈接:https://www.uj5u.com/houduan/444710.html
