返回
后端 Vue.js 以太坊 DApp 更新用户信息
前端
2024-02-12 12:50:11
大家好,欢迎来到本系列的最后一部分。如果你还没进入状况,那么我告诉你,我们将为以太坊区块链创建一个简单的去中心化应用程序。你可以随时查看第 1 和第 2 部分!
到目前为止,我们的应用程序能够从 Metamask 获取并显示帐户数据。但是,在更改帐户时,如果不重新加载页面,则不会更新。这显然不是我们想要的。因此,在本文中,我们将解决此问题并构建一个真正动态的应用程序。
首先,让我们更新App.vue
以监视当前帐户。为此,我们将使用watch
选项:
export default {
data() {
return {
account: null,
};
},
watch: {
'$store.state.web3.accounts'(accounts) {
if (accounts.length) {
this.account = accounts[0];
}
}
}
};
现在,无论何时更改帐户,account
数据都会自动更新。
接下来,让我们创建一个Profile.vue
组件来处理用户信息。首先,让我们在store/index.js
中定义一个名为profile
的模块:
export const state = () => ({
profile: null,
});
export const getters = {
getProfile(state) {
return state.profile;
},
};
export const mutations = {
setProfile(state, profile) {
state.profile = profile;
},
};
export const actions = {
async fetchProfile({ commit }) {
const web3 = this.$web3;
const accounts = await web3.eth.getAccounts();
const profile = await this.$contracts.Profile.methods.getProfile(accounts[0]).call();
commit('setProfile', profile);
},
async updateProfile({ commit }, profile) {
const web3 = this.$web3;
const accounts = await web3.eth.getAccounts();
await this.$contracts.Profile.methods.updateProfile(profile.name, profile.bio).send({ from: accounts[0] });
commit('setProfile', profile);
},
};
现在,让我们在Profile.vue
中使用此模块:
<template>
<div>
<h1>{{ profile.name }}</h1>
<p>{{ profile.bio }}</p>
<button @click="updateProfile">Update Profile</button>
</div>
</template>
<script>
import { mapState, mapActions } from 'vuex';
export default {
computed: {
...mapState({
profile: state => state.profile,
}),
},
methods: {
...mapActions([
'fetchProfile',
'updateProfile',
]),
async updateProfile() {
const profile = {
name: 'John Doe',
bio: 'Software Engineer',
};
await this.updateProfile(profile);
},
},
mounted() {
this.fetchProfile();
},
};
</script>
最后,我们需要在App.vue
中使用Profile
组件:
<template>
<div>
<h1>{{ account }}</h1>
<Profile />
</div>
</template>
<script>
import Profile from './Profile.vue';
export default {
components: {
Profile,
},
};
</script>
现在,你可以运行应用程序并尝试更新你的个人资料。
这就是本系列的全部内容。我希望你学到了一些东西。如果你有任何问题,请随时提问。