Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

VUE cannot update variable when API response

Tags:

vue.js

vuejs3

I want to update {{info}} value when the API is response.
But I don't know why there could be console log the response but cannot update the variable.
Any mistake I have make?

<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
    <script src="https://unpkg.com/vue@next"></script>
    <script src="https://unpkg.com/axios/dist/axios.min.js"></script>
</head>

<body>
    <div id="app">
        <p>{{info}}</p>
    </div>
</body>

</html>
<script>
    const { reactive,createApp, ref } = Vue;
    const app = {
         setup(){
            info="waiting......";
            axios
            .get('https://api.coindesk.com/v1/bpi/currentprice.json')
                    .then(response => (this.info = response))
                    .then(response => (console.log(response)));
            return {info};
        }
    }
    const myVue = Vue.createApp(app).mount("#app");

</script>
like image 895
龍が如く Avatar asked Aug 04 '26 11:08

龍が如く


1 Answers

here is a working example. If you want to use the composition API you have to make info a reactive variable with ref or reactive.

in this case you have to assign the new data to your reactive variable with the .value notation: info.value = data

composition API

const { createApp, onMounted, ref } = Vue;
const app = createApp({
  setup() {
    let info = ref('warning...')
    
    onMounted(() => {
      fetch('https://api.coindesk.com/v1/bpi/currentprice.json')
        .then(response => response.json())
        .then(data => {
          info.value = data
        });
    })

    return {
      info
    }
  }
});
app.mount("#app");
<script src="https://unpkg.com/vue@next"></script>
<div id="app">
  <p>{{info}}</p>
</div>

options API

Vue.createApp({
  data() {
    return {
      info: 'warning...'
    }
  },
  mounted() {
   fetch('https://api.coindesk.com/v1/bpi/currentprice.json')
    .then(response => response.json())
    .then(data => {
      this.info = data
    });
  }
}).mount('#options-api')
<script src="https://unpkg.com/vue@next"></script>
<div id="options-api">
  <p>{{ info }}</p>
</div>

console log the response but cannot update the variable

you have mixed the style from the composition API with the options API.

your code this.info = response will work with the options API (see my second example.) if you want to use the composition API you have to write info.value = response (see my first example).

note: I use the mounted hook only for demonstration purposes.

like image 131
wittgenstein Avatar answered Aug 07 '26 02:08

wittgenstein