在模板文件index.html里引入web3js;也可以通过npm i web3 ;还有把文件下载到项目中 import web3 from ‘x/web3.min.js’; 这里博主是在index.html里引入
- template.h5.html
<!DOCTYPE html>
<html lang="zh-CN">
<head>
<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, user-scalable=no, initial-scale=1.0, maximum-scale=1.0, minimum-scale=1.0, viewport-fit=cover">
<title>
<%= htmlWebpackPlugin.options.title %>
</title>
<link rel="icon" href="./static/logo1.png" />
//引入web3 1.5.5版本的
<script src="https://cdn.bootcdn.net/ajax/libs/web3/1.3.5/web3.min.js" type="text/javascript" charset="utf-8"></script>
<script>
window.addEventListener('load', async function () {
// 检查web3是否已经注入到(Mist/MetaMask)
if (typeof web3 !== 'undefined') {
// 使用 Mist/MetaMask 的提供者
web3js = new Web3(web3.currentProvider);
} else {
// 开发环境,如果在本地有以太坊的testrpc或者Ganache测试环境,则使用以下方式链接
web3js = new Web3(new Web3.providers.HttpProvider("http://localhost:8545"));
}
console.log('现在你可以启动你的应用并自由访问 Web3.js')
})
</script>
<style>
::-webkit-scrollbar{
display: none;
}
</style>
<script>
document.addEventListener('DOMContentLoaded', function() {
document.documentElement.style.fontSize = document.documentElement.clientWidth / 20 + 'px'
})
</script>
<link rel="stylesheet" href="<%= BASE_URL %>static/index.<%= VUE_APP_INDEX_CSS_HASH %>.css" />
</head>
<body>
<noscript>
<strong>Please enable JavaScript to continue.</strong>
</noscript>
<div id="app"></div>
<script>
/*BAIDU_STAT*/
</script>
</body>
</html>
- 开始使用
// 授权
async handleUserAuth(){
try{
const userAddress = await ethereum.request({ method: 'eth_requestAccounts' });
//调用者的钱包地址
console.log('userAddress',userAddress)
}catch(err){
uni.showToast({
title:err.message,
icon:'none'
})
}
},
//获取余额
async handleBalanceTap(){
//获取钱包地址
const accounts = await web3js.eth.getAccounts();
//获取钱包里的余额
const balance = await web3js.eth.getBalance(accounts[0]);
//格式化钱包余额为正常显示金额
const fromWei = await web3js.utils.fromWei(balance, 'ether');
console.log('我的余额',parseFloat(fromWei).toFixed(4))
},