2

I am trying to inject a javascript class as a plugin.

I get following error: Cannot read property 'log' of undefined

Class to be injected:

// helper/logging.service.js

export class LoggingService {
  constructor (prefix) {
      this.prefix = prefix
  }

  log (message) {
      console.log(`[${this.prefix}] ${message}`)
  }

  debug (message) {
      console.debug(`[${this.prefix}] ${message}`)
  }

  warn (message) {
      console.warn(`[${this.prefix}] ${message}`)
  }
}

Plugin:

// plugins/logger.client.js

import { LoggingService } from '../helper/logging.service'

export default ({ app }, inject) => {
  // create an instance of the LoggingService with the prefix 'My App'
  const logging = new LoggingService('My App')

  // inject the service, making it available in the context, component, store, etc.
  inject('logging', logging)
}

Usage:

// pages/logger.vue

<template>
  <button @click="log('Button clicked!')">Click Me</button>
</template>

<script>  
export default {
  name: 'ExamplePage',

  created () {
    this.$logging.log('Component created!')   // error is here
  },

  mounted () {
    this.$logging.debug('Component mounted!')
  },

  methods: {
    log (message) {
      this.$logging.warn(message)
    }
  }
}
</script>

UPDATE:

It looks like the plugin is not available in the created hook on client side, why? If I convert the plugin to a server-client side plugin, it works.

mahatmanich
  • 10,791
  • 5
  • 63
  • 82
  • 1
    Ok, I think I found the issue to be within the created() function. When I convert to a server side plugin, everything runs fine. However created() should be still on the client side, right? (At least that is what lifecycle suggests) – mahatmanich Jan 20 '22 at 08:47

0 Answers0