1

I am trying to fetch the data from API using the Vue.js but I am not able to achieve it. Here is my code.

<!DOCTYPE html>
<html>
    <head>
        <title>Vue.js test</title>
        <script src="https://cdn.jsdelivr.net/npm/vue/dist/vue.js"></script>
    </head>
    <body>
        <div id="app">
            <p>Total number of GitHub users: {{ info }}</p>
        </div>
        <script>
            import axios from 'axios';
            var app = new Vue({ 
            el: '#app',
            data () {
                return {
                    info: null
            }
        },
        mounted () {
            axios.get('https://api.github.com/users')
                .then(response => (this.info = response))
        }
        })
    
    })
        </script>
    </body>
</html>

Data is notbeing shown. Where am I doing wrong?

I have tried to fecth the data using axios but not getting the correct results.

xyz
  • 17
  • 3

1 Answers1

0
  1. Axios library was not loaded.
  2. the import axios from 'axios' does not work directly in the <script> tag

Have you got following JavaScript Error in the console?

Uncaught SyntaxError: Cannot use import statement outside a module

Check this Cannot use import statement outside a module(Vanilla Javascript)

  1. you don't need to import axios at all

Here is the working playground.

const app = new Vue({ 
  el: '#app',
  data() {
    return {
        info: null
    }
  },
  mounted() {
    axios.get('https://api.github.com/users')
        .then(response => (this.info = response.data.length))
  }
})
<!DOCTYPE html>
<html>
    <head>
        <title>Vue.js test</title>
        <script src="https://cdn.jsdelivr.net/npm/vue/dist/vue.min.js"></script>
        <script src="https://unpkg.com/axios@1.3.1/dist/axios.min.js"></script>
    </head>
    <body>
        <div id="app">
            <p>Total number of GitHub users: {{ info }}</p>
        </div>
    </body>
</html>
Tolbxela
  • 4,767
  • 3
  • 21
  • 42