How To Use Web3 in Vue Apps

Bayram EKER
5 min readAug 5, 2022

--

What exactly is Web 3.0?

Web2 and Web3 differ in a few ways, yet decentralization is a common theme in both. Web3 adds a few new features to the internet that we already use. It can be defined as the following:

  • Verifiable
  • Trustless
  • Self-governing
  • Permissionless
  • Distributed and robust
  • Stateful
  • With built-in payments

When working with Web3, programmers seldom create and deploy applications that rely on a single server or database (usually hosted on and managed by a single cloud provider).

Instead, Web3 applications either run on blockchains, decentralized networks of many peer to peer nodes (servers), or a combination of the two that forms a crypto-economic protocol. Many people in the Web3 community refer to these applications as “dapps” (decentralized apps), a word that you’ll see swimming around quite often.

An incentive for network members (developers) to deliver the best service possible is a key component of a robust and secure decentralized network.

Web3 is often discussed in conjunction with cryptocurrencies. This is due to the fact that many of these protocols rely heavily on cryptocurrencies. Anyone who wishes to become involved in one of the projects is given tokens (a cash incentive) in exchange for their time and effort.

In the past, cloud providers offered a wide range of services, including computation, storage, bandwidth, identity, hosting, and other online services.

Participating in the protocol in a variety of ways, both technical and non-technical, might be a source of income.

The protocol is often paid for by users in the same way that a cloud service provider like AWS charges its customers today. In Web3, however, the money flows directly to the network members. The elimination of middlemen that are both unneeded and inefficient is a hallmark of this sort of decentralization.

There are utility tokens provided by several online infrastructure protocols including Filecoin, LivePeer, Arweave, and The Graph. Many tiers of the network are rewarded with these tokens. This is how even native blockchain systems like Ethereum work.

Why We Prefer Vue.js

Vue.js is described as “a progressive framework for building user interfaces.” What differentiates this framework from other JavaScript web development frameworks is that its architecture is designed to be incrementally adaptable.

Vue has created a buzz in the web applications development ecosphere and is revolutionary in the sense that it has multiple use cases. It can be used to develop both desktop and mobile-based applications.

HTML extensions in addition to the JavaScript base have quickly seen Vue rise to a favored front-end tool that is being adopted by top tech companies like Adobe.

What are smart contracts?

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.

A single Web3 / Ethereum provider solution for all Wallets:

Web3Modal is an easy-to-use library to help developers add support for multiple providers in their apps with a simple customizable configuration.

Project setup

Project Codes

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:

  1. Install Web3Modal NPM package
npm install --save web3modal-vue# OR

yarn add web3modal-vue
  1. Then you can add Web3Modal to your Dapp as follows
<template>
<div id="app">
<web3-modal-vue
ref="web3modal"
:theme="theme"
:provider-options="providerOptions"
cache-provider
/>
</div>
</template>
<script>
import Web3ModalVue from "web3modal-vue";
import WalletConnectProvider from "@walletconnect/web3-provider";
import {web3Modal} from "./config/mixins";
import Header from "@/components/Header";
export default {
components: {
Header,
Web3ModalVue
},
mixins: [web3Modal],
data() {
return {
theme: 'light',
providerOptions: {
walletconnect: {
package: WalletConnectProvider,
options: {
infuraId: "-"
}
}
},
number: 0,
balance: 0,
}
},
created() {
if (window.matchMedia && window.matchMedia('(prefers-color-scheme: dark)').matches) {
this.theme = 'dark'
}
},
mounted() {
this.$nextTick(async () => {
const web3modal = this.$refs.web3modal;
this.$store.commit('setWeb3Modal', web3modal)
if (web3modal.cachedProvider) {
await this.$store.dispatch('connect')
this.subscribeMewBlockHeaders()
}
})
},
methods: {
connect() {
this.$store.dispatch('connect')
},
}
}
</script>
import {getLibrary} from "@/utils/web3";
import {ethers} from "ethers";
import {parseInt} from 'lodash'
const web3ModalStore = {
state: {
web3Modal: null,
library: getLibrary(),
active: false,
account: null,
chainId: 0,
},
mutations: {
setWeb3Modal(state, web3Modal) {
state.web3Modal = web3Modal
},
setLibrary(state, library) {
state.library = library
},
setActive(state, active) {
state.active = active
},
setAccount(state, account) {
state.account = account
},
setChainId(state, chainId) {
state.chainId = chainId
}
},
actions: {
async connect({state, commit, dispatch}) {
const provider = await state.web3Modal.connect();
const library = new ethers.providers.Web3Provider(provider) library.pollingInterval = 12000
commit('setLibrary', library)
const accounts = await library.listAccounts()
if (accounts.length > 0) {
commit('setAccount', accounts[0])
}
const network = await library.getNetwork()
commit('setChainId', network.chainId)
commit('setActive', true)
provider.on("connect", async (info) => {
let chainId = parseInt(info.chainId)
commit('setChainId', chainId)
console.log("connect", info)
});
provider.on("accountsChanged", async (accounts) => {
if (accounts.length > 0) {
commit('setAccount', accounts[0])
} else {
await dispatch('resetApp')
}
console.log("accountsChanged")
});
provider.on("chainChanged", async (chainId) => {
chainId = parseInt(chainId)
commit('setChainId', chainId)
console.log("chainChanged", chainId)
});
},
async resetApp({state, commit}) {
try {
await state.web3Modal.clearCachedProvider();
} catch (error) {
console.error(error)
}
commit('setAccount', null)
commit('setActive', false)
commit('setLibrary', getLibrary())
},
}
}
export default web3ModalStore;

Provider Options

These are all the providers available with Web3Modal and how to configure their provider options:

--

--

No responses yet