With Web3, it is possible to build decentralized applications on a blockchain network, giving users full ownership of their own data. The blockchain network uses smart contracts to handle all the backend logic of decentralized applications.
As the most popular, programmable blockchain network, Ethereum allows developers to build and manipulate decentralized applications (DApps), decentralized finance (DeFi), smart contracts, and non-fungible tokens (NFTs).
In this article, we’ll cover the basics of using Web3 in Vue applications, including the installation process and interacting with smart contracts. To follow along with this article, you’ll need the following:
Web3 is a new generation of the internet that is based on blockchain technology, promoting decentralization and token-based economics. Calling smart contracts and sending transactions make up most of the interactions on a blockchain network.
A smart contract is a self-executing computer software that lives on a blockchain network. The blockchain executes a smart contract as soon as it is deployed. When the contract is executed, it creates interfaces that DApps use to extend their functionality.
Consider the following simple Solidity smart contract:
// SPDX-License-Identifier: GPL-3.0 pragma solidity >=0.8.0; contract Contract { string private text; function speak() public view returns (string memory) { return text; } function changeText(string memory newText) public { text = newText; } }
When you deploy the contract above to the blockchain network, it creates two interface methods, speak
, which returns a text string, and changeText
, which changes the string that speak
returns.
If you already have a Vue project ready for integration, you can skip this section. If you don’t, create the project using the following command for npx package manager:
npx vue create web3-project
If you use the Yarn package manager, use the following command instead:
yarn vue create web3-project
In the menu prompts, select either Vue3 or Vue2. It doesn’t matter which one you choose because you can integrate Web3 in both of them the same way. After creating the project, write the following code in your App.vue
file:
<template> <div> <!-- connect-wallet button is visible if the wallet is not connected --> <button v-if="!connected">Connect wallet</button> <!-- call-contract button is visible if the wallet is connected --> <button v-if="connected">Call contract</button> {{ contractResult }} </div> </template> <script> export default { name: 'App', data() { return { connected: false, contractResult: '', } }, } </script>
In App.vue
, we have two buttons; the first is for connecting a wallet, and the second is for calling a smart contract method.
The call contract
button is hidden until the user connects their wallet to the web application. Our application uses the connected
state variable to save the wallet connection state.
In your project directory, run the command below to install the Web3 package using npm:
npm install web3
If you’re using Yarn, run the following command instead:
yarn add web3
After installing the package, we import Web3 into the App.vue
file and run the project to test its compatibility:
... <script> import Web3 from 'web3' export default { name: 'App', …
If you don’t receive any error messages besides Web3 is imported but never used
, Web3 is compatible with your framework. But, if the framework generates other errors, you have to switch to an older version of Vue. Web3 compatibility problems arise with the Webpack 5 module, which Vue 3 uses.
MetaMask is an application that allows users to store and connect their wallets to Web3 applications. Metamask can be installed in all major browsers. By connecting their wallet to a website, a user can do the following:
When you install the MetaMask extension in your browser, the extension creates a window.ethereum
object. Web3 applications use the window.ethereum
object to access the user’s wallet and connect to the Ethereum network.
The window.ethereum.request()
method prompts the user to connect their MetaMask wallet:
ethereum.request({ method: 'eth_requestAccounts' })
We can use this prompt to register a wallet connect event to our connect wallet
button. Add the following code to your App.vue
file:
<template> <div> <!-- "connect" click event is registered --> > <button v-if="!connected" @click="connect">Connect wallet</button> <button v-if="connected">Call contract</button> {{ contractResult }} </div> </template> <script> export default { name: 'App', data() { return { connected: false, contractResult: '', } }, > methods: { > connect: function () { > // this connects to the wallet > > if (window.ethereum) { // first we check if metamask is installed > window.ethereum.request({ method: 'eth_requestAccounts' }) > .then(() => { > this.connected = true; // If users successfully connected their wallet > }); > } > } > } } </script>
When the user clicks the connect wallet
button, a MetaMask prompt appears, allowing the user to select the accounts they want to connect. After the user connects their wallet, the connected
state variable in the App.vue
file becomes true
.
Deployed smart contracts create interfaces that Web3 applications interact with. To access these interfaces, we need to supply Web3 with the ABI, a description of the smart contract’s interface, and the contract address, the location of the contract on the Ethereum network.
Before writing this article, I deployed a smart contract on the Rinkeby test network. I’ll use its ABI and address in the following example, but if you already have a deployed smart contract, you can use that contract’s address and ABI instead of the ones included here.
To interact with deployed contracts, create an instance of Web3 using the window.ethereum
object:
let web3 = new Web3(window.ethereum);
Then, create a reference to the deployed contract using its ABI and address:
let contract = new web3.eth.Contract(abi, contractAddress)
After initializing the contract, you can interact with it. If the contract has an interface method called greet
, we call it using the code below:
contract.methods.greet().call()
Now, we’ll modify the call contract
button to call a contract with the greet
method of your deployed contract:
<!-- vue --> <button v-if="connected" @click="callContract">Call contract</button>
Next, create a callContract
method in the Vue object that the call contract
button calls:
callContract: function () { // method for calling the contract method let web3 = new Web3(window.ethereum); let contractAddress = '0xC0B2D76aB95B7E31E241ce713ea1C72d0a50588e'; let abi = JSON.parse(`[{"inputs": [],"stateMutability": "nonpayable","type": "constructor"},{"inputs": [],"name": "greet","outputs": [{"internalType": "string","name": "","type": "string"}],"stateMutability": "view","type": "function"}]`); let contract = new web3.eth.Contract(abi, contractAddress); contract.methods.greet().call() .then(result => this.contractResult = result); }
The callContract
method will be registered as the button’s click event and will call the greet
method in the deployed smart contract:
<template> <div> <button v-if="!connected" @click="connect">Connect wallet</button> <!-- "callContract" event handler is added --> > <button v-if="connected" @click="callContract">Call contract</button> <!-- displays the result of the contract --> {{ contractResult }} </div> </template> <script> import Web3 from 'web3' export default { name: 'App', data() { return { connected: false, contractResult: '', } }, methods: { connect: function () { let ethereum = window.ethereum; if (ethereum) { ethereum.request({ method: 'eth_requestAccounts' }) .then(() => { this.connected = true; }); } }, > callContract: function () { > // method for calling the contract method > let web3 = new Web3(window.ethereum); > let contractAddress = '0xC0B2D76aB95B7E31E241ce713ea1C72d0a50588e'; > let abi = JSON.parse(`[{"inputs": [],"stateMutability": "nonpayable","type": "constructor"},{"inputs": [],"name": "greet","outputs": [{"internalType": "string","name": "","type": "string"}],"stateMutability": "view","type": "function"}]`); > let contract = new web3.eth.Contract(abi, contractAddress); > contract.methods.greet().call() > .then(result => this.contractResult = result); > } } } </script>
After the user connects their wallet and calls the contract, the app should look something like the image below:
In this article, we learned how to use Vue to create a Web3 app using the Ethereum blockchain network, connect a MetaMask wallet, and interact with smart contracts. As you can see, integrating Web3 into a Vue application is fairly straightforward as long as you’re familiar with Solidity. Web3 offers major benefits for privacy and data ownership, and we explored some of the tools and concepts that make up this process, like smart contracts.
Debugging Vue.js applications can be difficult, especially when there are dozens, if not hundreds of mutations during a user session. If you’re interested in monitoring and tracking Vue mutations for all of your users in production, try LogRocket.
LogRocket is like a DVR for web and mobile apps, recording literally everything that happens in your Vue apps, including network requests, JavaScript errors, performance problems, and much more. Instead of guessing why problems happen, you can aggregate and report on what state your application was in when an issue occurred.
The LogRocket Vuex plugin logs Vuex mutations to the LogRocket console, giving you context around what led to an error and what state the application was in when an issue occurred.
Modernize how you debug your Vue apps — start monitoring for free.
Hey there, want to help make our blog better?
Join LogRocket’s Content Advisory Board. You’ll help inform the type of content we create and get access to exclusive meetups, social accreditation, and swag.
Sign up nowCompare Prisma and Drizzle ORMs to learn their differences, strengths, and weaknesses for data access and migrations.
It’s easy for devs to default to JavaScript to fix every problem. Let’s use the RoLP to find simpler alternatives with HTML and CSS.
Learn how to manage memory leaks in Rust, avoid unsafe behavior, and use tools like weak references to ensure efficient programs.
Bypass anti-bot measures in Node.js with curl-impersonate. Learn how it mimics browsers to overcome bot detection for web scraping.
One Reply to "Integrating Web3 into Vue applications"
thank you. i really liked this