我的Vuex状态下有一个对象数组,我想获取其中一个值作为另一个参数的默认值。在这种情况下,它适用于mainAccount
:
示例:
const store = new Vuex.Store({
state: {
AccountNums: [
{
label: 'Mister1',
value: '1234567890'
},
{
label: 'Mister2',
value: '9876543210'
}
],
mainAccount: this.state.AccountNums[1].value //this is where I want to use the val from the obj
}
但是,我遇到一个错误:
Cannot read property 'state' of undefined
当我删除this
关键字时,出现了另一个错误:
'state' is not defined
那我应该怎么做呢?
请注意,由于很多人都将访问此对象,因此我需要在Vuex状态内使用此AccountNums
对象。
谢谢!
答案 0 :(得分:1)
您不能以这种方式进行引用,因为尚未创建store
,有一种解决方法是先在外部声明您的accountNums
对象,然后像下面这样引用它
const accountNums = [
{
label: 'Mister1',
value: '1234567890'
},
{
label: 'Mister2',
value: '9876543210'
}
];
const store = new Vuex.Store({
state: {
AccountNums: accountNums,
mainAccount: accountNums[1].value
}
答案 1 :(得分:1)
此问题并非Vuex独有。每次定义JavaScript对象时,都无法在对象定义内引用该对象的其他属性。这就是为什么收到错误消息的原因-因为您是在对象定义中引用该对象。
解决方案非常简单。分别定义AccountNums
数组,然后在商店对象中对其进行引用。像这样:
const AccountNums = [
{
label: 'Mister1',
value: '1234567890'
},
{
label: 'Mister2',
value: '9876543210'
}
]
const store = new Vuex.Store({
state: {
AccountNums,
mainAccount: AccountNums[1].value //this refers to the const declared above
}