Vue应用程序(数据超出范围)-未在Proxy.calc中定义数据



*问候语堆栈溢出窥视。

我正在开发我的第一个Vue应用程序,但在使用find函数循环浏览我的金属列表以根据匹配类型道具提取特定重力值时遇到了问题。这个列表似乎超出了范围,我无法通过好的谷歌找到解决方案,所以我求助于大家。

TIA*

错误:

"vue@next:1751未捕获引用错误:未定义数据在Proxy.calc(index.html:101:45(在onClick(在compileToFunction进行评估(vue@next:15591:23(,:142:35(在callWithErrorHandling(vue@next:1688:24(在callWithAsyncErrorHandling(vue@next:1697:23(位于HTMLButtonElement.invoker(vue@next:9486:15(";

<script>
var app = Vue.createApp({
data: function() {  



return {

waxWeight: null,
isVisible: true,
buttonSize: null,
specificGravity: null,
metalType: null
}
},    
// <!-- COMPONENTS -->
components: {
},
// <!-- METHODS -->
// `this` inside methods point to the current Vue instance
methods: {
calc: function (waxWeight, buttonSize, metalType) {
var waxWeight = waxWeight
var buttonSize = buttonSize
var metalType = metalType
var metals = {metals:[
{ type: 'silver', specificGravity: 10.3 },
{ type: 'wGold14', specificGravity: 12.1 },
{ type: 'wGold18', specificGravity: 11.5 },
{ type: 'yGold14', specificGravity: 13.6 }]}
// method does not have access to data list 
const specificGravity = data.metals.find(function(elem){
if(elem.name == metalType) 

return elem.specificGravity;
alert(metalType)
});
}
},
})
app.mount('#app')
</script> 

我不确定你想在这个函数中做什么,但我会尽力帮助你。

问题是数据不能像那样访问,数据是一个返回JSON对象的函数。因此,假设您想要访问Data中声明的isVisible。您使用this.isVisible

但是我不明白你为什么需要访问那里的数据。您似乎想要访问json对象内部的数组,所以请尝试metals.metals.find(...)。如果你想访问数组金属,当你调用elem.name时,你总是会得到未定义的,因为这不是对象的键,你应该使用elem.type。这是我为你做的一支代码笔,用来举例说明我所说的

很抱歉回答太长,如果这对你没有帮助,请提供更多的上下文,这样我可以帮助你

此处解决了初始问题:https://codepen.io/pandemicprogrammer/pen/GROWqwR

我错误地引用了数组对象,并将JSON数据放错了位置。


methods: {
calc: function (waxWeight, buttonSize, metalType) {
alert("test")
var waxWeight = waxWeight
var buttonSize = buttonSize
var metalType = metalType
var metals = {metals:[
{ type: 'silver', specificGravity: 10.3 },
{ type: 'wGold14', specificGravity: 12.1 },
{ type: 'wGold18', specificGravity: 11.5 },
{ type: 'yGold14', specificGravity: 13.6 }]}

const specificGravity = 
metals.metals.find(function(elem){

if(elem.type == metalType) {

alert(elem.specificGravity)
return elem.specificGravity;
}

});
}
},

最新更新