如何从 Vue 中的方法访问数据?

How to access data from methods in Vue?

如何从 methods 访问数据函数中的 response
this 在这种情况下不起作用,this 只会让我访问 methods 范围 属性:

<script>
export default {
    data: function () {
        return {
            prompt: '',
            response: '',
            show: false
        }
    },

    methods: {
        getResponse: function () {
            let text
            const data = {
                prompt: this.prompt,
                temperature: 0.5,
                max_tokens: 64,
                top_p: 1.0,
                frequency_penalty: 0.0,
                presence_penalty: 0.0,
            }    

            fetch("https://api.openai.com/v1/engines/text-curie-001/completions", {
            method: "POST",
            headers: {
                "Content-Type": "application/json",
                Authorization: `Bearer ${process.env.VUE_APP_OPENAI_SECRET}`,
            },
            body: JSON.stringify(data),
            })
            .then (response => {
                if (response.ok) {
                    return response.json()
                }else{
                    throw new Error('We got an error')
                }
            })
            .then (result => {
                text = result.choices[0].text
                console.log(text)
                })
            .catch( (err) => {
                console.log('ERROR:', err.message)
            })

            this.response = text
        }
    }
}
</script>

像这样的东西应该可以工作

<template>
  <div>
    <pre>{{ response }}</pre>
    <button @click="getResponse">call it</button>
  </div>
</template>

<script>
export default {
  data() {
    return {
      prompt: '',
      response: '',
    }
  },

  methods: {
    async getResponse() {
      const data = {
        prompt: this.prompt,
        temperature: 0.5,
        max_tokens: 64,
        top_p: 1.0,
        frequency_penalty: 0.0,
        presence_penalty: 0.0,
      }

      try {
        const response = await fetch(
          'https://api.openai.com/v1/engines/text-curie-001/completions',
          {
            method: 'POST',
            headers: {
              'Content-Type': 'application/json',
              Authorization: `Bearer ${process.env.VUE_APP_OPENAI_SECRET}`,
            },
            body: JSON.stringify(data),
          }
        )
        if (response.ok) {
          const result = await response.json()
          this.response = result.choices[0].text
        }
      } catch (err) {
        throw new Error('We got an error', err)
      }
    },
  },
}
</script>