Home > Software design >  How could I fetch json data, and show the data in template in a very simple vuejs3 demo
How could I fetch json data, and show the data in template in a very simple vuejs3 demo

Time:03-12

Sorry about my limited English, and I am very new in vuejs 3.

For some reason I would like to using vuejs without build tools. I am trying to import a very simple json into the demo code, and show the data from json in the template.

My code

<!doctype html>
<html>
<head>
<meta charset="utf-8">
<title>Untitled Document</title>
</head>

<body>
<script src="https://unpkg.com/vue@3"></script>
<div id="app">{{info.name}}</div>
<script>
    import { someData } from './data.json';
  Vue.createApp({
    data() {
      return {
          info: someData
      }
    }
  }).mount('#app')
</script>
</body>
</html>

JSON Code

{"name":"John", "age":30, "car":null}

The error is: Uncaught SyntaxError: Cannot use import statement outside a module

CodePudding user response:

<!doctype html>
<html>
<head>
<meta charset="utf-8">
<title>Untitled Document</title>
</head>
 
<body>
<script src="https://unpkg.com/vue@3"></script>
<script src="https://code.jquery.com/jquery-3.5.1.min.js"></script>
<div id="app">
    {{info.name}}
</div>
<script>
  let someData = $.ajax({url:"./data.json",async:false});
  someData = JSON.parse(someData.responseText)
  Vue.createApp({
    data() {
      return {
          info: someData
      }
    }
  }).mount('#app')
</script>
</body>
</html>
 

CodePudding user response:

The error says it all: you can't use import statement outside a module.

Try adding type=setup as in the following:

<script type="module">
  /* JavaScript module code here */
</script>
  • Related