我正在尝试将 javascript 类作为插件注入。
我收到以下错误: 无法读取未定义的属性“日志”
要注入的类:
// 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}`)
}
}
插入:
// 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)
}
用法:
// 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>
更新:
看起来插件在客户端创建的钩子中不可用,为什么?如果我将插件转换为服务器客户端插件,它就可以工作。