属性 in Data 在 methods() 方法中未定义

Property in Data is undefined inside methods() method

我是 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>

如能就我无法访问 'data' 中的属性提供任何帮助,我们将不胜感激

你不应该混合组合和选项API(this不一样,而且组合API中没有方法),尝试像下面的片段(组合API) 或者您可以将方法移动到选项 API (删除 setup 函数):

const { ref } = Vue
const App = {
  setup() {
    const geneMutations = ref(['ACTC', 'MYBPC3'])
    let queryConstraints = ref([])
    const selectedGeneMutation = ref('')
    const getGeneMutationData = () =>  {
      queryConstraints.value.push({
        fieldPath: selectedGeneMutation.value,
        opStr: '==',
        value: true
      })
    }
    return {  
      geneMutations, queryConstraints, selectedGeneMutation, getGeneMutationData
    };
  }
}
Vue.createApp(App)
  .mount('#app')
<script src="https://unpkg.com/vue@3.2.29/dist/vue.global.prod.js"></script>
<div id="app">
  <select v-model="selectedGeneMutation">
    <option v-for="geneMutation in geneMutations" :key="geneMutation">{{geneMutation}}</option>
  </select>
  <input type="button" @click="getGeneMutationData" value="Get results" />
  <h3>{{ queryConstraints }}</h3>
</div>

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

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

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

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