接上文

接上文部署完智能合约成功后,我们可以新建一个vue工程,写个基本的展示来调用智能合约

<template>
  <div class="hello">

    <h1> 账户: {{ account }}</h1>
    <h1> 余额:{{ balance }}</h1>
    <h1> 合约的counter: {{ num }}</h1>
 
  </div>
</template>

<script>
export default {
  data() {
    return {
      account: "1111",
      balance: -1,
      num:0
    };
  },
  mounted() {
    // 利用web3连接区块连
    var Web3 = require("web3");

    var web3 = new Web3(
      new Web3.providers.HttpProvider("http://localhost:8545")
    );

    var t = this;
    web3.eth.getAccounts().then(function (accounts) {
      var acc = accounts[0];
      console.log(this);
      t.account = acc;
      web3.eth.getBalance(acc).then(function (balance) {
        var amount = web3.utils.fromWei(balance, "ether");
        t.balance = amount;
        console.log(amount);
      });
    });

    //调用合约 参数1:abi  参数2:合约地址  
    var myContract = new web3.eth.Contract(
      [
        {
          inputs: [],
          stateMutability: "nonpayable",
          type: "constructor",
        },
        {
          inputs: [],
          name: "getCounter",
          outputs: [
            {
              internalType: "uint256",
              name: "",
              type: "uint256",
            },
          ],
          stateMutability: "view",
          type: "function",
        },
        {
          inputs: [
            {
              internalType: "uint256",
              name: "step",
              type: "uint256",
            },
          ],
          name: "kipCounter",
          outputs: [],
          stateMutability: "nonpayable",
          type: "function",
        },
      ],
      "0x5C77a4F7B1A8F6D3A317afe232bdcD5e0BCC756B",
      {
        from: "0xF4155fc6814985f905a17931497356d49874BD61", // default from address
        gasPrice: "20000000000", // default gas price in wei, 20 gwei in this case
      }
    );

    //调用合约的getCounter方法
    myContract.methods.getCounter().call({from:'0xF4155fc6814985f905a17931497356d49874BD61'},function(error,result){
          // console.log("counter:" ,result);
          t.num = result;  
          //结果为1
    });

   //调用合约的kipCounter方法
    myContract.methods.kipCounter(6).send({from: '0xF4155fc6814985f905a17931497356d49874BD61'})
    .then(function(){
      //重新调用合约的getCounter方法,得到最新结果
      myContract.methods.getCounter().call({from:'0xF4155fc6814985f905a17931497356d49874BD61'},function(error,result){
          // console.log("counter:" ,result);
          t.num = result;
          //结果为6
    });
});


  }, 
  props: {
    msg: String,
  },
  methods() {},
};
</script>

<!-- Add "scoped" attribute to limit CSS to this component only -->
<style scoped>
h3 {
  margin: 40px 0 0;
}
ul {
  list-style-type: none;
  padding: 0;
}
li {
  display: inline-block;
  margin: 0 10px;
}
a {
  color: #42b983;
}
</style>

 参数描述:

abi: 上文中提到过的地方

合约地址: 上文执行出来的地址

 

 

Logo

为开发者提供学习成长、分享交流、生态实践、资源工具等服务,帮助开发者快速成长。

更多推荐