返回

后端 Vue.js 以太坊 DApp 更新用户信息

前端

大家好,欢迎来到本系列的最后一部分。如果你还没进入状况,那么我告诉你,我们将为以太坊区块链创建一个简单的去中心化应用程序。你可以随时查看第 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>

现在,你可以运行应用程序并尝试更新你的个人资料。

这就是本系列的全部内容。我希望你学到了一些东西。如果你有任何问题,请随时提问。