我对vue和vuex有点新意,所以试图 grab 它 . 该应用程序工作正常,但不是严格的做事方式 .
我正在我的操作中进行异步API调用,然后将操作中的变异与检索到的数据一起作为有效负载提交 . 然后突变更新状态 . 该操作将在我的视图组件的beforeCreated选项上调度 .
我目前收到错误,不想简单地关闭严格 .
“错误:[vuex]不要在突变处理程序之外改变vuex存储状态 . ”
我的商店:
import Vue from 'vue'
import Vuex from 'vuex'
import Web3 from 'web3'
Vue.use(Vuex)
export const store = new Vuex.Store({
strict: true,
state: {
web3: {
address: null,
balance: null,
isInjected: false,
error: null
}
},
mutations: {
registerWeb3Instance (state, payload) {
state.web3 = payload
}
},
actions: {
accounts (context) {
var web3Inst = typeof window.web3
if (web3Inst !== 'undefined') {
var metamask = true
} else {
metamask = false
}
var web3 = new Web3(window.web3.currentProvider || new Web3.providers.HttpProvider('http://localhost:7545'))
var accounts = web3.eth.accounts
accounts = accounts.map((account) => {
var acc = {
address: account,
balance: 0,
isInjected: metamask,
error: null
}
web3.eth.getBalance(account, function (err, res) {
if (err) {
console.log(err)
}
acc.balance = parseInt(res, 10)
})
return acc
})
context.commit('registerWeb3Instance', accounts[0])
}
}
})
我的组件:
<template>
<div class="container">
<div v-if="web3.isInjected" class="alert alert-success" id="has-metamask" role="alert">
<i aria-hidden="true" class="fa fa-check"></i> Metamask installed
</div>
<div v-else class="alert alert-danger" id="no-meta-mask" role="alert">
<i aria-hidden="true" class="fa fa-times"></i> MetaMask not installed
</div>
<div id="balances">
<div class="alert alert-primary" role="alert">
<p><strong>{{ web3.account }}</strong></p>
<button type="button" class="btn btn-primary"><span class="badge badge-light" id="balance-count"></span>{{ web3.balance }} Wei</button></div>
</div>
</div>
</template>
<script>
export default {
name: 'HelloMetamask',
computed: {
web3 () {
return this.$store.state.web3
}
},
beforeCreate: function () {
this.$store.dispatch('accounts')
}
}
</script>
<!-- Add "scoped" attribute to limit CSS to this component only -->
<style scoped>
</style>
非常感谢 .