Home > Software engineering >  How to access data from methods in Vue?
How to access data from methods in Vue?

Time:05-18

How can I access response in data function from methods?
this won't work in this case, this will only get me access to a methods scope property:

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

CodePudding user response:

Something like this should work

<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>
  • Related