What methods can I employ to implement global variables within a VueJS component?

How do I access global variables within a VueJS component?

I'm attempting to retrieve the `url` variable in the fetch function within the `methods` section, but it seems to be causing issues.

var products = [];
var url = '/data-set.json';

const app = new Vue({
    el: "#app",
    data: {
        products: []
    },
    methods: {
        handleKeyPress(event) {
            console.log(event.key);
            this.showProducts()
        },
        showProducts(products) {
          const htmlSnippet = products
                .slice(0, 3)
                .map((product) => {

                    var replaceTerm = searchElement.value;
                    var regExp = new RegExp(replaceTerm, "gi");

                    return `
                    <li class="productWrapper">
                    <div class="imgProduct">
                        <img src="https://someurl.com/products/320x240/${product.imageKey}.jpg" alt="">
                    </div>

                    <div class="infoProduct">
                        <h2>${product.title} - </h2>
                        <h3>${product.id.replace(regExp, `<span class="highlight">$&</span>`)}</h3>
                        <br>
                        <p>${product.description}</p>
                    </div>
                </li>
            `;
                })
                .join("");

            productListContainer.innerHTML = htmlSnippet;
        },
        fetch(url).then(res => res.json())
            .then((result) => {
                products = result
            })
            .catch(error => { throw error });
    }
})

Answer №1

Upon reviewing the code you provided, it appears that there are several issues that need to be addressed:

First and foremost, the fetch function seems to be calling another function that requires importing beforehand. This invocation should ideally be encapsulated within its own function wrapper as demonstrated below:

    import fetch from '@/api/fetch'

let produits = [];
const url = '/dataset.json';

const vm = new Vue({
    el: "#app",
    data: {
        produits: []
    },
    methods: {
        handleKeyUp(event) {
            console.log(event.key);
            this.displayProducts()
        },
        displayProducts(products) {
            const htmlString = products
                .slice(0, 3)
                .map((produit) => {

                    var replace = searchBar.value;
                    var re = new RegExp(replace, "gi");

                    return `
                    <li class="produitWrapper">
                    <div class="imgProduit">
                        <img src="https://d1tydw6090df56.cloudfront.net/products/320x240/${produit.imageKeyHashes}.jpg" alt="">
                    </div>

                    <div class="infosProduit">
                        <h2>${produit.title} - </h2>
                        <h3>${produit.mpn.replace(re, `<span class="highlight">$&</span>`)}</h3>
                        <br>
                        <p>${produit.description}</p>
                    </div>
                </li>
            `;
                })
                .join("");

            productsList.innerHTML = htmlString;
        },
        fetch(url) {
            fetch(url).then(res => res.json())
            .then((output) => {
                produits = output
            })
            .catch(err => { throw err });
        }
    }
})

Additionally, it is unclear where you intend to call the fetch function in your code. It seems like you are attempting to trigger the fetching of information within the displayProducts function upon a user action in the template. If this is the case, the URL should be passed as a parameter to the function. While I may not have provided a direct solution to your issue without further context, I believe these pointers should guide you in the right direction.

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

Can Node.js be executed using Bash commands on a Windows operating system?

Exploring Node.js has been my latest endeavor. Upon downloading Node.js for Windows, I found myself faced with the command prompt version tailored for Windows. This got me thinking - is there a way to set up a UNIX environment for Node.js on a Windows syst ...

What is the best way to obtain the value of a radio button using ajax?

Here is the search button in my PHP file. I am unsure of how to connect the radio button to the JavaScript file. <button id="submit">Search</button> This is the starting point in the JavaScript file var xhr = new XMLHttpRequest(); f ...

Leverage JavaScript to add the rel=0 attribute to a specific URL

Currently, I am integrating videos into my WordPress website using a plugin and I'm looking for a way to ensure that all the YouTube URLs contain rel=0 to eliminate related videos at the end. Can anyone suggest the best approach to achieve this? Any ...

Is it possible to pass the chart type as a property when using vue-chart.js?

Is it possible to pass the chart type as a property with vue-chart.js? I would love to see some example source code. Can you please provide guidance on this? ...

What is the best way to convert this jQuery code into an AngularJS implementation?

I'm diving into the world of AngularJS and looking for a more elegant solution using AngularJS principles Controller $scope.filter = function($event, active, id) { var html = ""; if(active){ $http({method: 'GET& ...

Guide to using JavaScript to populate the dropdown list in ASP

On my aspx page, I have an ASP list box that I need to manually populate using external JavaScript. How can I access the list box in JavaScript without using jQuery? I am adding the JavaScript to the aspx page dynamically and not using any include or impor ...

Cannot assign value to property x on y as it is not an object - dealing with Multidimensional Arrays

I'm experimenting with creating a multidimensional array that looks like this: var minutes = []; for (let i = 1; i < 10; i++) { minutes.push(i); } var works = [{ startTime: 80000, endTime: 150000 }, { startTime: 200000, endTime: 400000 ...

Tips for creating a nested div structure using JavaScript

I am facing an issue with my results object that includes data like Creation_date and approval_date. I have put the results in a loop in JavaScript and created nested divs. However, when I debug it, the divs are not nested as expected. Each one seems to ...

Creating a WordPress post popup using Ajax with SimpleModal and jQuery

I tried to follow the instructions provided in this tutorial but unfortunately, I couldn't get it to work. This is the process I followed: 1 / Including in the header <script src="http://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js" ...

Searching with parameters in the MVC framework involves utilizing specific criteria to filter data and

I am looking to create a user-friendly page where users can search for the following criteria: Search work Category Price AdType Location It is important that users are able to save their search settings in the database and easily retrieve them by copyi ...

Save the modal to a variable and display it when clicked

I am trying to create a modal and display it when a user clicks a button. However, I seem to be facing an issue where nothing happens when the button is clicked and there are no errors in the console. $( '.outlet' ).on('click', functio ...

Utilizing Browser and Operating System Information as Body Class

In order to achieve pixel-perfect styling, I want to include the OS and browser information in the body class. This is necessary because fonts may appear differently depending on the OS/browser configuration. After some research and experimentation, I came ...

Using SVG graphics as data labels in a HighChart stacked column chart

I am attempting to generate a stacked column chart in Highcharts with SVG images as x-axis labels, similar to the image displayed here: https://i.stack.imgur.com/y5gL1.png I have managed to achieve this with individual data points per label (non-stacked ...

A guide on sending user input to PHP, executing SQL commands, and showing PHP output

My program operates as follows: there are three buttons on an HTML page that link to three different PHP files which generate XML results based on fixed SQL commands in Oracle. When a user clicks on one of the buttons, for example: <p><input ...

iOS & Safari IntersectionObserver: A seamless navigation experience for Apple device users

I have a goal to dynamically change the position of a video element when a user scrolls to that specific section. I am utilizing the Intersection Observer API as I need to manage page scrolling within an AdForm Banner/iFrame context. Below is the snippet ...

Optimizing Array Comparison in JavaScript and Angular 2

In my Angular 2 .ts (TypeScript) file, I have declared two arrays as shown below: parentArray: Array<Model> initialized with {a, b, c, d} modifiedArray: Array<Model> modified with data {c, e, f, g} How can I efficiently determine the differ ...

Utilizing Json data with Jquery for dynamically placing markers on Google Maps

Seeking assistance as I am currently facing a problem where I need to loop through JSON data and add it as markers on Google Maps, but unfortunately, it only returns null value. Is there a way to automatically connect this to JSON? My plan is to have a Gr ...

How can I retrieve an array from the server side using AngularJS?

Currently, I'm involved in developing a web application meant for team collaboration. While the login and signup pages have been set up, other members of my team are focusing on the server (built with node.js and express framework) and database aspect ...

illustrating a large image on a canvas

When I initially drew an image on the canvas, it looked like this: https://i.sstatic.net/t6sIC.png Now, I am attempting to reload the same image into the canvas, and it appears like this: https://i.sstatic.net/xLiO7.png Here is my code: var ctx = element.c ...

Exploring a new approach to organizing data with LocalStorage and AngularJS

I developed an application that utilizes LocalStorage to store data. The issue I encountered was storing a large number of objects under a single key, causing the DOM to become blocked. This is due to the necessity of parsing and stringifying the JSON dat ...