在 Nuxt 2.0 使用 Web3Modal 2.0 套件連接多種加密貨幣錢包

做法

建立專案。

1
2
npm init nuxt-app web3modal-v2-nuxt-example
cd web3modal-v2-nuxt-example

安裝依賴套件。

1
npm i @wagmi/core @web3modal/ethereum @web3modal/html ethers

修改 nuxt.config.js 檔。

1
2
3
4
5
6
7
{
// ...

build: {
transpile: ['@web3modal', '@walletconnect', '@wagmi']
}
}

修改 pages/index.vue 檔。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
<template>
<div>
<client-only>
<w3m-core-button />
<button @click="sign">
Sign
</button>
</client-only>
</div>
</template>

<script>
import Vue from 'vue'
import { configureChains, createClient, getAccount, signMessage } from '@wagmi/core'
import { goerli, mainnet } from '@wagmi/core/chains'
import { EthereumClient, modalConnectors, walletConnectProvider } from '@web3modal/ethereum'
import { Web3Modal } from '@web3modal/html'

Vue.config.ignoredElements = [
'w3m-core-button'
]

export default {
name: 'IndexPage',
mounted () {
// define constants
const projectId = '5b71f5ba1a93e7ee227d6f2f023b946d'
const chains = [mainnet, goerli]

// configure wagmi client
const { provider } = configureChains(chains, [walletConnectProvider({ projectId })])
const wagmiClient = createClient({
autoConnect: true,
connectors: [
...modalConnectors({ appName: 'web3Modal', chains })
],
provider
})

// create ethereum and modal clients
const ethereumClient = new EthereumClient(wagmiClient, chains)
const web3Modal = new Web3Modal(
{
projectId
},
ethereumClient
)

web3Modal.subscribeModal(({ open }) => {
const account = getAccount()
console.log(account)
})
},
methods: {
async sign () {
const signature = await signMessage({
message: 'Hello, World!'
})
console.log(signature)
}
}
}
</script>

啟動網頁。

1
npm run dev

程式碼