要么改变世界,要么适应世界

链博——DAPP练手项目(三)

2023-01-02 11:06:11
274
目录

原文再续,书接上回。

这一回我们主要完成Vue项目和智能合约交互。完整代码请参考【链接】

首页

在首页主要是请求全部的文章:

import Web3 from "web3";
import ChainBlogJson from "@/build/ChainBlog.json";
// ....
methods: {
    // 读取 json 文件,利用 abi 和地址初始化合约
    async f() {
      //   var web3 = new Web3(Web3.givenProvider || "ws://localhost:8545");
      var web3 = new Web3("ws://localhost:7545");
      const networkId = await web3.eth.net.getId();
      const abi = ChainBlogJson.abi;
      const contractAddress = ChainBlogJson.networks[networkId].address;
      const contract = new web3.eth.Contract(abi, contractAddress);
      this.contract = contract;
      this.getAllBlog();
    },
    // 调用合约中的函数
    async getAllBlog() {
      this.contract.methods
        .getAll()
        .call()
        .then((blogs) => {
          this.blogs = blogs;
        })
        .catch((e) => {
          console.log(e);
        });
    },
  },
  mounted() {
    this.f();
  },

新增文章页面

在这个页面中,我们要获取MetaMask中活跃的账户,即正在使用的账户,然后连接智能合约,调用智能合约,流程还是差不多:

submit() {
  if (this.content == "" || this.title == "")
    alert("Content and title can't be empty!");
  // 获取 metamask 中启动的账号
  window.ethereum
    .enable()
    .then((accounts) => {
      this.contract.methods
        .addBlog(this.title, this.summary, this.content)
        .send({
          // 利用授权的第一个,即正在活跃的账号进行提交文章
          from: accounts[0],
          gas: 3000000,
        })
        .then((res) => {
          alert("发表成功");
          this.$router.push({ name: "home" });
        })
        .catch((e) => {
          console.log(e);
        });
    })
    .catch((e) => {
      console.log(e);
    });
},

注意!我们这里使用send函数而不是call函数,因为后者没法更新状态

文章详情页面

这里有一点要注意,如果该文章的作者与正在登录的一致,我们给予删除和修改的权限

<!-- 只有文章所有者才有权删除和修改 -->
<div v-if="is_owner">
  <button class="delete_btn" v-on:click="deleteClick">删除</button>
  <button class="modify_btn" v-on:click="modifyClick">修改</button>
</div>
<!-- ....... -->
<script>
    // .......
    // 检查该文章是不是当前 metamask 中活跃的账户所写的
    checkOwner() {
      window.ethereum
        .enable()
        .then((accounts) => {
          if (accounts[0].toLowerCase() == this.blog.author.toLowerCase()) {
            this.is_owner = true;
          }
        })
        .catch((e) => {
          console.log(e);
        });
    },
</script>

修改文章页面

这里和新增文章页面差不多,只不过要先请求旧的文章填充表单,然后再提示用户修改。


后话

此项目仅用于学习,请勿用于其他违反道德和法律的事项!

参考链接

【1】ChainBlog(本项目完整源码).https://github.com/YaleXin/ChainBlog

【2】web3.js中文文档.https://learnblockchain.cn/docs/web3.js/

【3】Solidity中文文档.https://learnblockchain.cn/docs/solidity/

【4】truffle文档.https://learnblockchain.cn/docs/truffle/getting-started/running-migrations.html

【5】开发、部署第一个DApp.https://learnblockchain.cn/2018/01/12/first-dapp/

【6】DApp教程:用Truffle 开发一个链上记事本.https://learnblockchain.cn/2019/03/30/dapp_noteOnChain/

【7】Vue.js https://cn.vuejs.org/

历史评论
开始评论