简体   繁体   English

如何为Nuxt.js创建插件?

[英]How to create plugin for Nuxt.js?

This is my rpc.js plugin file: 这是我的rpc.js插件文件:

const { createBitcoinRpc } = require('@carnesen/bitcoin-rpc')

const protocol = 'http'
const rpcuser = 'root'
const rpcpassword = 'toor'
const host = '127.0.0.1'
const port = '43782'
const rpcHref = `${protocol}://${rpcuser}:${rpcpassword}@${host}:${port}/`
const bitcoinRpc = createBitcoinRpc(rpcHref)

export default ({ app }, inject) => {
  inject('bitcoinRpc', (method) =>
    bitcoinRpc(method).then((result) => console.log('That was easy!', result))
  )
}

This is my nuxt.config.js file: 这是我的nuxt.config.js文件:

...
plugins: [{ src: '@/plugins/gun.js' }, { src: '@/plugins/rpc.js' }],
...

If I call this.$bitcoinRpc('getnewaddress') somewhere in the component methods, then I get an error, but if I call this method inside the rpc plugin itself, then everything works as expected: 如果我在组件方法中的某个地方调用this.$bitcoinRpc('getnewaddress') ,则会收到错误消息,但是如果我在rpc插件本身中调用此方法,则一切都会按预期进行:

// plugins/rpc.js:
// Declare constants and inject above
...
bitcoinRpc('getnewaddress').then((result) =>
  console.log('That was easy!', result)
)

I get the expected result in the terminal: 我在终端中得到了预期的结果:

That was easy! 2N8LyZKaZn5womvLKZG2b5wGfXw8URSMptq 14:11:21

Explain what I'm doing wrong? 解释我做错了什么?

The method outlined by me was correct. 我概述的方法是正确的。

The error that occurred was caused by the fact that on the client side it was not possible to use the server side libraries. 发生的错误是由于在客户端无法使用服务器端库这一事实引起的。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM