gpt4 book ai didi

javascript - Data 中的属性在methods() 方法中未定义

转载 作者:行者123 更新时间:2023-12-03 08:10:16 25 4
gpt4 key购买 nike

我是 Vue 的新手,所以到目前为止我试图了解基础知识。我正在使用 Vue 3。

我的意图是:

  • 使用数组中的项目作为选项创建一个选择,这可行。
  • 单击按钮后,存储选择的值,这也有效。
  • 使用选择的值作为对象的键值来推送对象

正是在最后阶段发生了错误,特别是 getGeneMutationData: () => this.queryConstraints.push({

错误:

Uncaught TypeError: Cannot read properties of undefined (reading 'queryConstraints')
at Proxy.getGeneMutationData (Query.vue?12c2:46:14)
at eval (runtime-dom.esm-bundler.js?3191:380:1)
at callWithErrorHandling (runtime-core.esm-bundler.js?a261:155:1)
at callWithAsyncErrorHandling (runtime-core.esm-bundler.js?a261:164:1)
at callWithAsyncErrorHandling (runtime-core.esm-bundler.js?a261:174:1)
at HTMLButtonElement.invoker (runtime-dom.esm-bundler.js?3191:366:39)

我不确定为什么这不起作用,根据文档,我不确定这些方法有什么不同:

data() {
return { count: 4 }
},
methods: {
increment() {
// `this` will refer to the component instance
this.count++
}
}

这是我的代码的最小化:

<template>
<select v-model="selectedGeneMutation">
<option v-for="geneMutation in geneMutations" :key="geneMutation">{{geneMutation}}</option>
</select>
<input type="button" @click="getGeneMutationData">Get results</input>
</template>

<script>
export default {
name: 'Home',
data: () => ({
geneMutations: ['ACTC',
'MYBPC3'
],
queryConstraints: [],
selectedGeneMutation: ''
}),
setup() {},
methods: {
getGeneMutationData: () => this.queryConstraints.push({
fieldPath: this.selectedGeneMutation,
opStr: '==',
value: true
})
}
};
</script>

任何关于为什么我无法访问“数据”中的属性的帮助将不胜感激

最佳答案

您正在使用 Arrow Function 。它是有限的,并且没有自己的绑定(bind)到 this,这就是您的方法失败的原因。您所引用的文档使用传统的函数表达式。

所以在你的情况下尝试这个:

getGeneMutationData: function () {
this.queryConstraints.push({
fieldPath: this.selectedGeneMutation,
opStr: "==",
value: true,
});

编辑:实际上尼古拉·帕维切维奇的答案是正确的。是的,使用传统的函数表达式可以解决您的问题,但是,似乎混合了组合和选项 API(或者更确切地说不理解两者之间的区别)是导致问题的首要原因。在 Vue 3 中,当您使用 composition API 时您没有使用这个setup() 方法返回一个对象,并且它的所有属性都暴露给组件的其余部分。

关于javascript - Data 中的属性在methods() 方法中未定义,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/71054760/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com