• 自学Vue开发Dapp去中心化钱包(二)


    目录​​​​​​​​​​​​​​

    前言

    一、Vue基础学习

    二、开始使用

    1.安装Node.js

    2.安装淘宝npm

     3.安装vue-cli

    4.创建一个Vue项目

     6.idea打开项目

    7.安装依赖环境

    8.安装其他

    三、Vue部分组件使用

    1.Vue全局加载

    2.vue-router

    3.element-ui组件

    4.vue-i18n组件

    国际化js文件示例

    使用场景示例

    5.vuex组件

    模块化

    index.js

     state.js

    mutations.js

     getter.js

     action.js

    store的使用

    效果

    6.ethers.js

    总结


    前言

    前篇确定了技术选型,门户使用Vue前端开发,此篇文章主要记录本人自学Vue以及实操搭建前端框架的过程和遇到的前端知识点和技术瓶颈难题(ps对大佬这都不是难题)。


    一、Vue基础学习

    从零学习(前提有jquery,js等开发经验)Vue,选择先通过视频学习,跟着老师实际上手操作。

    所看视频来自狂神bilibili的视频:【狂神说Java】Vue最新快速上手教程通俗易懂_哔哩哔哩_bilibili

    老师讲解比较风趣,到位,从零讲起,学习了Vue的框架,Vue的基础语法v-bind,v-if,v-for及事件click等使用,Vue的双向绑定,Vue组件化开发,Vue异步通信等。

    二、开始使用

    1.安装Node.js

    下载Node.js 下载 | Node.js 中文网

    下载后双击安装next到最后即可。

    安装后测试是否安装成功

    1. cmd最好使用管理员模式
    2. //显示安装的nodejs版本
    3. node -v
    4. //显示安装的npm版本
    5. npm -v

    2.安装淘宝npm

    安装国内淘宝的镜像,因为npm相关的资源国外节点可能会失败。

    1. cmd管理员模式
    2. npm install cnpm

     3.安装vue-cli

    1. //-g代表全局使用
    2. npm install vue-cli -g
    3. vue list
    4. //npm未安装成功时使用
    5. cnpm install vue-cli -g

    4.安装webpack

    1. npm install webpack -g
    2. webpack -v
    3. npm install webpack-cli -g
    4. webpack-cli -v
    5. //打包
    6. webpack
    7. //可实现监听文件发生变化自动打包
    8. webpack--watch

    4.创建一个Vue项目

    打包方式webpack

    1. cd d:
    2. vue init webpack myvue
    3. //确认项目名称后,后续选择否即可

    这里可以直接选择安装上Vue-router路由,也可以直接N,进入项目后手动安装。

     

     最后选择自己执行npm install即可。

     6.idea打开项目

    目录结构应该是这样的

     

     重要的文件有package.json,包含了所有安装的依赖及包的版本;

    config里面主要是打包相关的参数,访问地址设置以及后续可能使用到的浏览器跨域问题在config/index.js文件中参数配置。

    7.安装依赖环境

    使用idea终端操作即可

    1. npm install
    2. //运行
    3. npm run dev

     可能遇到的问题:

    1.npm不是内部或外部命令。

    解决File-> Settings -> Tools -> Terminal -> Shell path中内容由cmd.exe修改为C:\Windows\System32\cmd.exe全路径。

    再不行时,桌面idea工具图标右键->属性->兼容性->以管理员身份运行此程序,重新idea。

    2.npm install失败,检查是否提示了package.json中组件版本过高或者过低问题;试试cnpm install

    8.安装其他

    1. //安装vue-router,--save也可以写--S,指在本项目中安装
    2. npm install vue-router --save
    3. //安装axios
    4. npm install axios
    5. //安装element-ui
    6. npm i element-ui -S
    7. //安装vuex,vuex-persistedstate,后续会介绍使用此组件
    8. cnpm install vuex@3.6.2 vuex-persistedstate --save
    9. //安装vue-i18n国际化
    10. npm install vue-i18n@8.26.5

    9.安装后启动

    npm run dev

    三、Vue部分组件使用

    1.Vue全局加载

     main.js中全局加载组件

    1. //main.js中全局加载
    2. import Vue from 'vue'
    3. import App from '@/App'
    4. import router from '@/router'
    5. import store from '@/store/index';
    6. import ElementUI from 'element-ui';
    7. import 'element-ui/lib/theme-chalk/index.css';
    8. import VueI18n from 'vue-i18n';
    9. import { getMonthFirstDay,getFormatDate,getMonthLastDay,addNotBlankRule,parseTime, resetForm, addDateRange, selectDictLabel, selectDictLabels, handleTree } from "@/utils/yufu/commonUtils";
    10. // 全局方法挂载
    11. Vue.prototype.parseTime = parseTime
    12. Vue.prototype.resetForm = resetForm
    13. Vue.prototype.addDateRange = addDateRange
    14. Vue.prototype.selectDictLabel = selectDictLabel
    15. Vue.prototype.selectDictLabels = selectDictLabels
    16. Vue.prototype.handleTree = handleTree
    17. Vue.prototype.addNotBlankRule = addNotBlankRule
    18. Vue.prototype.getMonthLastDay = getMonthLastDay
    19. Vue.prototype.getFormatDate = getFormatDate
    20. Vue.prototype.getMonthFirstDay = getMonthFirstDay
    21. Vue.prototype.msgSuccess = function (msg) {
    22. this.$message({ showClose: true, message: msg, type: "success" });
    23. }
    24. Vue.prototype.msgError = function (msg) {
    25. this.$message({ showClose: true, message: msg, type: "error" });
    26. }
    27. Vue.prototype.msgInfo = function (msg) {
    28. this.$message.info(msg);
    29. }
    30. Vue.prototype.myConfirm = function(msg,f1,f2){
    31. this.$confirm(msg,"Warning", {
    32. confirmButtonText: "Yes",
    33. cancelButtonText: "No",
    34. type: "warning"
    35. }).then(f1).then(f2).catch(()=>{
    36. //this.msgInfo("已取消");
    37. });
    38. }
    39. Vue.prototype.myConfirm2 = function(msg,title){
    40. return this.$confirm(msg,title||"操作信息", {
    41. confirmButtonText: "确定",
    42. cancelButtonText: "取消",
    43. type: "warning"
    44. }).catch(()=>{
    45. this.msgInfo("已取消");
    46. });
    47. }
    48. //设置全局缓存常量
    49. window.cacheData = {}
    50. /*---------挂载全局使用-----------*/
    51. Vue.use(ElementUI);
    52. Vue.use(VueI18n);
    53. const i18n = new VueI18n({
    54. locale: 'en', //切换语言
    55. messages: {
    56. zh: require('@/language/zh.js'),
    57. en: require('@/language/en.js'),
    58. },
    59. });
    60. new Vue({
    61. el: '#app',
    62. router,
    63. store,
    64. i18n,
    65. render: h => h(App),
    66. components: { App },
    67. template: ''
    68. })

    2.vue-router

    创建index.js:vue的路由组件,router目录下创建index.js

    1. //项目目录下创建router目录,router目录下创建index.js
    2. //index.js
    3. //导入依赖
    4. import Vue from 'vue'
    5. import Router from 'vue-router'
    6. //页面组件
    7. import TransferAccounts from '@/views/TransferAccounts'
    8. //Vue加载使用
    9. Vue.use(Router);
    10. //解决因版本问题多次点击后前端console报错问题
    11. const originalPush = Router.prototype.push
    12. Router.prototype.push = function push (location) {
    13. return originalPush.call(this, location).catch(err => err)
    14. }
    15. export default new Router({
    16. mode: 'history', // 去掉url中的#
    17. routes: [
    18. {
    19. path:'/transferAccounts',//指定路由路径
    20. name:"transferAccounts",//起个别名,可忽略
    21. component: TransferAccounts//这个是路由的组件,就是需要跳转到的组件页面
    22. }
    23. ]
    24. })

     其他地方使用,使用前需要main.js全局挂载,见3.1Vue全局加载

    1. //js代码调用时
    2. this.$router.push('/login')
    3. //template中使用
    4. //import先引入组件,然后template中使用router-link to路由路径。
    5. //必须加上
    6. id="app">
    7. Hello App!

    8. "/">Go to Home
    9. "/about">Go to About

3.element-ui组件

文档路径:Element - The world's most popular Vue UI framework

  1. import Vue from 'vue';
  2. import ElementUI from 'element-ui';
  3. import 'element-ui/lib/theme-chalk/index.css';
  4. import App from './App.vue';
  5. Vue.use(ElementUI);
  6. new Vue({
  7. el: '#app',
  8. render: h => h(App)
  9. });

4.vue-i18n组件

  1. import Vue from 'vue'
  2. import VueI18n from 'vue-i18n'
  3. Vue.use(VueI18n)
  4. const i18n = new VueI18n({
  5. locale: 'en', //切换语言
  6. messages: {
  7. zh: require('@/language/zh.js'),
  8. en: require('@/language/en.js'),
  9. },
  10. });
  11. new Vue({
  12. el: '#app',
  13. router,
  14. store,
  15. i18n,
  16. render: h => h(App),
  17. components: { App },
  18. template: ''
  19. })

国际化js文件示例

 zh.js

  1. //zh.js
  2. export const lang = {
  3. swap1: '转账',
  4. swap2: '充值',
  5. };

en.js

  1. //en.js
  2. export const lang = {
  3. swap1: 'Transfer',
  4. swap2: 'Recharge',
  5. };

使用场景示例

  1. 1.标签中
  2. {{ $t('lang.swap1') }}

  3. 2.script中
  4. this.$message.error(this.$t('lang.swap5')+'');
  5. 3.标签上,使用`:`绑定使用
  6. "$t('lang.swap58')" show-word-limit v-model="ruleForm.to">
  7. <el-dialog :title="$t('lang.swap74')" :visible.sync="dialogVisible" width="30%">
  8. <AddBindAcctDialog :visible.sync="dialogVisible" @getList="getList"/>
  9. el-dialog>

5.vuex组件

Vuex 是一个专为 Vue.js 应用程序开发的状态管理模式 + 库,采用集中式存储管理应用的所有组件的状态,解决多组件数据通信Vuex 是什么? | Vuex

为什么我要使用,我做的这个钱包门户设计小狐狸钱包多个账户地址的切换,实时监听切换并刷新展示页面数据。因为store可以存储数据状态,发生改变时只需管理数据的实际状态就可以达到所有组件中数据的唯一性,实时性。

 官方提供的最简单的store

  1. import { createApp } from 'vue'
  2. import { createStore } from 'vuex'
  3. // 创建一个新的 store 实例
  4. const store = createStore({
  5. state () {
  6. return {
  7. count: 0
  8. }
  9. },
  10. mutations: {
  11. increment (state) {
  12. state.count++
  13. }
  14. }
  15. })
  16. const app = createApp({ /* 根组件 */ })
  17. // 将 store 实例作为插件安装
  18. app.use(store)

模块化

  1. ├── index.html
  2. ├── main.js
  3. ├── api
  4. │ └── ... # 抽取出API请求
  5. ├── components
  6. │ ├── App.vue
  7. │ └── ...
  8. └── store
  9. ├── index.js # 我们组装模块并导出 store 的地方
  10. ├── actions.js # 根级别的 action
  11. ├── mutations.js # 根级别的 mutation
  12. └── modules
  13. ├── cart.js # 购物车模块
  14. └── products.js # 产品模块

本人项目中的模块化结构

实际代码

index.js

  1. //index.js
  2. import Vue from 'vue';
  3. import Vuex from 'vuex';
  4. import state from '@/store/state';
  5. import * as actions from '@/store/actions';
  6. import * as mutations from '@/store/mutations';
  7. import * as getters from '@/store/getters';
  8. import createPersistedState from 'vuex-persistedstate';
  9. Vue.use(Vuex);
  10. const store = new Vuex.Store({
  11. state,
  12. actions,
  13. mutations,
  14. getters,
  15. plugins: [
  16. createPersistedState({
  17. paths: ['isConnectWallet', 'account'],
  18. }),
  19. ],
  20. });
  21. export default store

 state.js

  1. export default {
  2. //provider对象
  3. provider: {},
  4. //合约对象
  5. contracts: {},
  6. //签名对象
  7. signer: {},
  8. //小狐狸钱包的账户address
  9. account: '',
  10. net: 0,
  11. //gas费,后续可能要用
  12. gasPrice: 0,
  13. //钱包余额
  14. balance: '0.0',
  15. //作为是否链接登录到小狐狸钱包的标志
  16. isConnectWallet: false,
  17. //绑卡列表数据,用于下拉框
  18. accountList: [],
  19. //交易计数,用于发生交易时同步刷新交易记录列表
  20. tradeCounter: 0,
  21. };

mutations.js

  1. export const saveProviderStore = (state, provider) => {
  2. state.provider = provider;
  3. };
  4. export const saveContractsStore = (state, contracts) => {
  5. state.contracts = contracts;
  6. };
  7. export const saveAccountStore = (state, account) => {
  8. state.account = account;
  9. };
  10. export const saveBalanceStore = (state, balance) => {
  11. state.balance = balance;
  12. };
  13. export const saveNetStore = (state, net) => {
  14. state.net = net;
  15. };
  16. export const saveGasPriceStore = (state, gasPrice) => {
  17. state.gasPrice = gasPrice;
  18. };
  19. export const saveIsConnectWallet = (state, isConnectWallet) => {
  20. state.isConnectWallet = isConnectWallet;
  21. };
  22. export const saveSigner = (state, signer) => {
  23. state.signer = signer;
  24. };
  25. export const saveAccountList = (state, accountList) => {
  26. state.accountList = accountList;
  27. };
  28. export const saveTradeCounter = (state, tradeCounter) => {
  29. state.tradeCounter = tradeCounter;
  30. };

 getter.js

  1. // 获取最终的状态信息
  2. export const provider = state => state.provider;
  3. export const contracts = state => state.contracts;
  4. export const signer = state => state.signer;
  5. export const account = state => state.account;
  6. export const net = state => state.net;
  7. export const gasPrice = state => state.gasPrice;
  8. export const balance = state => state.balance;
  9. export const isConnectWallet = state => state.isConnectWallet;
  10. export const accountList = state => state.accountList;
  11. export const tradeCounter = state => state.tradeCounter;

 action.js

  1. // 触发保存方法
  2. export const SET_PROVIDER = ({ commit }, payload) => {
  3. commit('saveProviderStore', payload);
  4. };
  5. export const SET_CONTRACTS = ({ commit }, payload) => {
  6. commit('saveContractsStore', payload);
  7. };
  8. export const SET_ACCOUNT = ({ commit }, payload) => {
  9. commit('saveAccountStore', payload);
  10. };
  11. export const SET_BALANCE = ({ commit }, payload) => {
  12. commit('saveBalanceStore', payload);
  13. };
  14. export const SET_NET = ({ commit }, payload) => {
  15. commit('saveNetStore', payload);
  16. };
  17. export const SET_GAS_PRICE = ({ commit }, payload) => {
  18. commit('saveGasPriceStore', payload);
  19. };
  20. export const SET_IS_CONNECT_WALLET = ({ commit }, payload) => {
  21. commit('saveIsConnectWallet', payload);
  22. };
  23. export const SET_SIGNER = ({ commit }, payload) => {
  24. commit('saveSigner', payload);
  25. };
  26. export const SET_ACCOUNT_LIST = ({ commit }, payload) => {
  27. commit('saveAccountList', payload);
  28. };
  29. export const SET_TRADE_COUNTER = ({ commit }, payload) => {
  30. commit('saveTradeCounter', payload);
  31. };
  32. .........其他代码
  33. export const setProvider = ({commit},address) => {
  34. let web3Provider;
  35. if (window.ethereum) {
  36. web3Provider = window.ethereum;
  37. .....获取web3钱包中的一些熟悉,地址,provider,合约对象等
  38. //commit('saveAccountStore', address);//另外一种方式
  39. SET_ACCOUNT({commit},address);
  40. SET_PROVIDER({commit},provider);
  41. SET_CONTRACTS({commit},daiContract);
  42. SET_IS_CONNECT_WALLET({commit},true);
  43. SET_SIGNER({commit},signer);
  44. }
  45. };

store的使用

  1. 1.action.js中要改变数据状态时
  2. //commit('saveAccountStore', address);//另外一种方式
  3. SET_ACCOUNT({commit},address);
  4. 2.组件中,使用语法糖获取值
  5. import {mapState} from "vuex";
  6. export default {
  7. computed: {
  8. ...mapState(['account']),
  9. getAccount() {
  10. if (this.account) {
  11. return '0x...' + this.account.substring(this.account.length - 4, this.account.length);
  12. } else {
  13. return '';
  14. }
  15. },
  16. },
  17. }
  18. 3.组件中,不使用语法糖获取值
  19. this.$store.getter.account;
  20. 4.组件中使用语法糖调用方法
  21. methods: {
  22. handleLogin() {
  23. this.$store.dispatch('connectWallet');
  24. },
  25. }
  26. 5.组件中改变store数据状态
  27. let balanceStr = '0.0';
  28. this.$store.dispatch('SET_BALANCE', balanceStr);

效果

6.ethers.js

  1. 1.install安装
  2. 2.js文件中引入即可使用
  3. import * as ethers from 'ethers';
  4. 获取钱包余额
  5. const balance = await daiContract.balanceOf(address);
  6. let balanceStr = ethers.utils.formatUnits(balance, 18);


总结

主要学习使用Vue的基础语法,然后跟随老师实际操作,最后自己搭建Vue前端的整体框架。安装依赖组件,并学习各个组件的用法。接下来文章介绍Vue框架使用中遇到的问题及解决方法。打脸待续

  • 相关阅读:
    Nuxt.js Next.js Nest.js
    linux内核I2C子系统详解——看这一篇就够了
    如何使用自己公司的数据,训练聊天机器人,如何选择算法
    南大通用GBase8s 常用SQL语句(256)
    冥想第六百一十一天
    使用Sqoop命令从Oracle同步数据到Hive,修复数据乱码 %0A的问题
    基于微信小程序便民服务系统(微信小程序毕业设计)
    Numpy函数详解
    Debezium系列之:永久保存history topic中的数据
    7 和其他程序协同工作
  • 原文地址:https://blog.csdn.net/xieedeni/article/details/126303187