Vue.js does not support the usage of external JSON files directly within HTML documents

I'm encountering issues fetching data from an external JSON file for a specific variable. I suspect that the problem lies in using Vue.js within the HTML, as it seems to be having trouble interpreting my code correctly.:joy: jsfiddle
Additionally, I'm struggling to access values from the JSON file.

new Vue({
        el: '#app',
        data() {
            return {
                searchResult: [],
                search: '',
            }
        },

        created: function() {
            this.searchResult = [
                {
                    "id": 0,
                    "title": "d",
                    "img": "src"
                }
            ];
        },

        computed: {
            filteredName: function() {
                return this.searchResult.filter((x) => {
                    return x.title.match(this.search)
                });
            },
            allOK: function () {
                if (this.search.valueOf() === "") {
                    return false
                } else {
                    return true
                }
            },
            hrefResult: function () {
                return "/item?=" + this.searchResult.id
            }
        }
    });

Does anyone have any suggestions on how to resolve this dilemma? :(

Answer №1

The issue lies in utilizing ECMAScript Imports without a module script. The import keyword is only valid within <script type="module">, leading to a syntax error: Unexpected identifier where the import statement exists (attempting to import json/products.json).

There exist a few remedies that necessitate a modern browser (with potential polyfills for older browsers).

Solution 1: Modify your script by adding type="module", and ensure using relative paths in the import pathway. demonstration

<!-- within HTML file -->
<script type="module">
  import products from './json/products.json.js'

  new Vue({
    el: '#app',
    data () {
      return {
        items: products
      }
    }
  })
</script>

Solution 2: Retrieve the external JSON file instead of importing it. demo

<!-- inside HTML file -->
<script>
  (async () => {
    const productsResponse = await fetch('./json/products.json');
    const products = await productsResponse.json();

    new Vue({
      el: '#app',
      data () {
        return {
          items: products
        }
      }
    })
  })();
</script>

Alternatively, consider shifting to vue-cli projects, which feature transpiling in its build, enabling the use of imports for external JSON files. demo

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Struggling with serving static content on NodeJS using Express.js

I set up a basic NodeJS and Express server on my development machine running Windows 10. var express = require('express'); var app = express(); app.use(express.static('app')); app.use('/bower_components', express.static(&apo ...

Attempting to implement a smooth fade effect on my image carousel using React-Native

Struggling to animate this image carousel in reactNative and feeling lost. Despite reading the documentation on animations, I can't figure out how to implement it properly. My attempts keep resulting in errors. Any assistance would be greatly apprecia ...

Unable to create circular dots within the Slick Slider widget

While attempting to create a slider with dots, I encountered an issue where the dots appeared as ellipses instead of circles, despite setting the width and height to be the same. For instance, I specified width: 12px; height: 12px; but it resulted in a sha ...

The margin 0 auto feature is ineffective, and instead, the target is activated upon the page's initial loading

As a beginner in CSS, I am encountering some issues with the HTML page of my application. I am currently working on an app and aiming to create a login view where the login form appears either after a voice command or button click. I am facing two main pro ...

ng-show and ng-hide toggling for the active row

I have a single table where I am implementing row hide and show functionality using Angular for editing and saving purposes. So far, everything works as expected. $scope.init=function(){ $scope.editable=true; } Now, when I click on the edit button ...

How to build a Python dictionary from a pandas DataFrame

In my pandas dataframe, I have three columns labeled as Lot Number, Price, and Image Id. My task is to generate a JSON file structured in the following format: https://i.sstatic.net/mtzHL.png {'1200-1300':{'LOT3551': [9082327, 9082329] ...

The useEffect function is not being executed

Seeking assistance from anyone willing to help. Thank you in advance. While working on a project, I encountered an issue. My useEffect function is not being called as expected. Despite trying different dependencies, I have been unable to resolve the issue ...

Ensure that the image within the child div occupies the entire height of the parent div

I'm having a bit of trouble figuring this out and could use some input: There's a parent div with an unspecified height, determined by its content. Inside this parent div are two 'child' elements; however, I want only one to dictate t ...

Refreshing a single HTML element in ASP.NET MVC - the simple way!

Recently, I put together an image gallery using the unite gallery jquery plugin and now I want to change up the images it displays. My plan is to have a button labeled "art" that, when clicked, triggers a function to update the directory path and load ne ...

Issue: React child components cannot be objects (received: object with keys)

Hey everyone, I could really use some help figuring out what I'm doing wrong. Here is the error message I'm receiving: Error: Objects are not valid as a React child (found: object with keys {id, title, bodyText, icon}). If you meant to render a ...

Is the "add" feature malfunctioning?

My code is experiencing an issue where the URL and ID are not being passed correctly from one function to another. When I click on a link that contains the add() function, it fails to capture the URL and ID. <a href="#" style="color:#FFF;" onclick="add ...

Creating a JavaScript object and retrieving the values of numerous input fields with identical classes

I have encountered an issue that I need assistance with: <input title="1" type="text" class="email"> <input title="2" type="text" class="email"> <input title="3" type="text" class="email"> The HTML code above shows my attempt to extract ...

Experiencing difficulties with node and asynchronous programming

I'm attempting to use async-waterfall in order to fetch data from an API, save it as JSON, and then store it in a database. Here is a snippet of the code I have so far. Can someone assist me with this process? async.waterfall([ function getBo ...

Trouble retrieving all rows from mySQL to JSON Object, only receiving the first

In this snippet: $sql ="SELECT * FROM parcours"; $r = mysqli_query($con,$sql); $result = array(); while($res = mysqli_fetch_array($r)){ $result[] = $res; } echo json_encode(array("result"=>$result)); Only the first row of my database query is being ...

Clicking on the element will not cause the body to scroll

For some reason, I need to keep the onclick function, but I'm struggling to make it work as intended. What I want is for the body to slide to the next logo when the previous logo is clicked. This is a simplified version of what I have: <div class ...

Implementing Batch File Uploads using Typescript

Is there a way to upload multiple files in TypeScript without using React or Angular, but by utilizing an interface and getter and setter in a class? So far I have this for single file upload: <input name="myfile" type="file" multi ...

Gaining a comprehensive understanding of media queries

Hello everyone, I need some help with media queries. I've been working on a website that is already responsive. However, I am required to write the code in a child theme rather than directly in the original files. When I attempt to add new media quer ...

Ways to Retrieve JavaScript Variable inside HTML Tags in a JSP

I am currently facing a requirement where I must assign js variables to html input tag ids. For example: <input type='text' id='(here I need js variable)'/> I am aware that one way to achieve this is by creating the entire elem ...

What is the best way to pass a module from the controller to a Jade/Pug template and then use it as an argument in an event handler within the template?

I passed the module 'naija' to a template from the controller in this way: res.render('testing', {title:"filter setting page", nigeria:naija }); The func ...

A dynamic modal window built with ReactJS

I am struggling to understand how to make my app function properly. There is a component called ContactAdd that should render the component ModalWindow when clicked. The ModalWindow component requires a parameter called isOpened={this.state.open}. How c ...