Read Ethereum Smart Contract from a Vue Application

Now that we have a smart contract deployed locally we can query the local Ethereum blockchain node from our Vue application to begin seeing how a web3 application fits in a web application.

Let's start by creating a new Vue component called GreetingDapp.vue and replace the img element and HelloWorld component in our Vue application with this new component.

Within the GreeterDapp component, add the following two lines to the top of the script element:

import { ethers } from 'ethers'
import Greeter from '../../artifacts/contracts/Greeter.sol/Greeter.json'

This imports ethers.js that we use to interact with Ethereum as well as the Greeter ABI in the form of a JSON file.

Next implement the data function in the GreeterDapp component that will hold the state of this component:

data() {
  return {
    address: "Copy the contract address of your Greeting smart contract here",
    greeting: '',
    greetingFromDapp: ''
  }
},

The contract address is the value when print to the screen when you ran the deploy.js script in the previous lesson.  Copy that value from the terminal into the address field of the component.

After this step add a methods object to the component where we'll start to interact with Ethereum using the imported ethers.js library.


methods: {

  async fetchGreeting() {
    if (typeof window.ethereum !== 'undefined') {
      const provider = new ethers.providers.Web3Provider(window.ethereum)
      const contract = new ethers.Contract(this.address, Greeter.abi, provider)
      try {
        this.greetingFromDapp = await contract.greet()
        console.log('data: ', this.greetingFromDapp)
      } catch (err) {
        console.log("Error: ", err)
      }
    }
  }
}

This greeting method will call the greet function on our smart contract and store the value in the greetingFromDapp field of our component.

Lastly update the HTML of this component to call this fetchGreeting method when a button is clicked and display the greeting in the UI.

<template>
<div>
  <h1>Greeting Dapp</h1>

  <button @click="fetchGreeting">Get Greeting</button>

  <div v-if="greetingFromDapp">
    Greeting from Ethereum Smart Contract: {{greetingFromDapp}}
  </div>
  
</div>
</template>

When you click the Get Greeting button, the Vue application will call the greet method and return the value of the default greeting!

greeting-dapp-ethereum.png 438.09 KB


Thanks for watching!
© 2022 Nimble Labs, LLC. All rights reserved.