The Vue feature responsible for displaying information on the webpage is currently not working as expected

I'm in the process of developing a settings page for a project. This particular page is based on HTML and utilizes JSON to store data, with Vue 3 being used to display the information on the page. However, I've encountered an issue where the data is being gathered correctly, but Vue isn't replacing the variables as expected. Is there something wrong with my approach?

HTML:

<!DOCTYPE html>
<html lang="en" xmlns:v-on="http://www.w3.org/1999/xhtml">
    <head>
        <meta charset="UTF-8" />
        <title>Settings</title>
        <link href='./favicon.ico' rel='icon'>
        <script src="scripts/vue.js"></script>
    </head>
    <body>
        <div id="settings">
            <span>Background: {{ background }}</span><br />
            <span>Columns: {{ columns }}</span><br />
            <span>Group:</span><br/>
            &nbsp;&nbsp;&nbsp;<span>Width: {{ group_width }}</span><br/>
            &nbsp;&nbsp;&nbsp;<span>Color: {{ group_color }}</span>
        </div>
        <script src="scripts/settings.js" type="text/javascript, module"></script>
    </body>
</html>

settings.js:

import Vue from './vue';

    var request = new XMLHttpRequest();
    var settings_object;
    request.open('GET', 'data/settings.json', true);
    request.send(null);
    request.onreadystatechange = function () {
        if (request.readyState === 4 && request.status === 200) {
            settings_object = JSON.parse(request.responseText);
            var bgval = settings_object.background;
            var cval = settings_object.columns;
            var gwval = settings_object.group.width;
            var gcval = settings_object.group.color;
    
            // Used exclusively for testing the collection of data.
            alert('Background: ' + bgval + '\n' +
            'Columns: ' + cval + '\n' +
            'group_width' + gwval);
    
            new Vue({
                el: '#settings',
                data: {
                    background: bgval,
                    columns: cval,
                    group_width: gwval,
                    group_color: gcval,
                },
            });
        }
    };

settings.json:

{
    "background": "connected_dots",
    "columns": 2,
    "group": {
        "width": 3,
        "color": "custom"
    }
}

Answer №1

@Lawrence Cherone is absolutely correct in stating that the XMLHttpRequest() function should be placed inside a hook such as created() or mounted(). Following the XHR call, you can assign values from the hook by:

this.yourVariableDefinedInData = value.

It's important to note that using

.bind(this) 

is crucial to ensure the correct scope of "this" within the context of

request.onreadystatechange = function () {

The following code snippet should function correctly:

var vueMain = new Vue({
    el: '#vue-main',
    data: {
        background: '',
        columns: '',
        group_width: '',
        group_color: '',
    },
    computed: {
        field0: function(){
            var classCss = 'field margin-mobile-fix';
            if (this.expandBaseData===false){
                classCss += ' hidden';
                // vueMenu.menuVisible=false;
            }else{
                classCss +=" opacity0 hidden-show";
                // vueMenu.menuVisible=true;
            }
            return classCss;
        },
    },
    mounted() {
            var request = new XMLHttpRequest();
            var settings_object;
            request.open('GET', 'data/settings.json', true);
            request.send(null);
            request.onreadystatechange = function () {
                if (request.readyState === 4 && request.status === 200) {
                    settings_object = JSON.parse(request.responseText);
                    this.bgval = settings_object.background;
                    this.cval = settings_object.columns;
                    this.gwval = settings_object.group.width;
                    this.gcval = settings_object.group.color;
                    alert('Background: ' + this.bgval + '\n' +
                    'Columns: ' + this.cval + '\n' +
                    'group_width' + this.gwval);
                }
            }.bind(this)
}
})

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

Handling iOS callbacks in case a Firebase query fails to execute (using Swift for Firebase)

I have a question about querying .childAdded in my database. Everything works fine when data is present at the specified location. However, if there is no data at that location, the query does not fire and I am unable to use snapshot.exists because the qu ...

Obtain $stateParams excluding UI-navigation

Is there a way to access $stateParams without using a <ui-view> tag in the HTML? I'm trying to make this code function properly: .config([ '$locationProvider', '$stateProvider', function($locationProvider, $stateProvide ...

How can I retrieve the decimal x and y coordinates when the mouse is moved in Typescript Angular?

I am in the process of transitioning my user interface from Flash/Flex, where it stores values in decimal format. I need to access and reuse these values. Here is a demo showcasing my problem. Here is a snippet: import { Component, Input } from '@an ...

Issue with C++ libcurl causing segmentation fault in write callback function

I'm in a rush and looking for a quick solution. I came across another SO question and attempted to apply the code provided there. I am working with a few rest services (not multithreaded) that return json data, but when the CURLOPT_WRITEFUNCTION is tr ...

Changing the value of a JSON object

My goal is to update a value in a JSON file by removing the last character from a URL. I wrote the following code, but unfortunately, it doesn't seem to be making any changes. I'm a bit lost on what went wrong... def modify_json(file): with ...

Troubleshooting the Confirm Form Resubmission problem on my website

Hello everyone! I'm working on a website and facing an issue where refreshing the page triggers a confirm form resubmission prompt. Could someone please advise me on how to resolve this? Thank you in advance! ...

What is preventing me from utilizing my JavaScript constructor function externally?

I have a question about how I create my object: var myViewModel = new MyViewModel("other"); Why am I unable to call myViewModel.setHasOne(value) from outside the viewmodel? Whenever I try, I encounter this error message: Uncaught TypeError: Cannot ca ...

Unable to input text using Python Selenium in a textbox

Currently, I am attempting to input text into a specific textarea HTML element using Python Selenium: <div class="spk-c spH-d"><div id="gwt-uid-23" class="sppb-a"> <div class="sppb-b spk-b">For example, flowers or used cars</div> & ...

Encountered an error stating 'Cannot read property 'user' of undefined' while attempting to generate a user document during account creation using Firebase

I'm having trouble adding the user ID to a new collection named 'accounts' during account creation. I keep encountering an error that says 'Cannot read property 'user' of undefined'. Can someone please help me troubleshoo ...

Comparison: NumberFormatter versus NumberFormat in PHP and JavaScript

My attempts to format currency seem to yield inconsistent results. Using PHP with the NumberFormatter class, here's a snippet of my code: $number = 5125.99; echo getInternationallyFormattedCurrency($number, 'tl-PH', 'PHP'); echo & ...

extract information from the request header

One of the functionalities in my application involves making Ajax requests to the server. $.ajax({ type: "get", beforeSend: function (jqXHR) { jqXHR.setRequestHeader(ZO_KEY1, _key1); jqXHR.setReq ...

problem decoding json data from external server

I have a custom Grease Monkey script that is responsible for collecting data from a game and sending it to my server for tracking our team's progress. This process involves multiple Ajax requests between the GM script and the game, followed by sending ...

JavaScript - The onkeypress event continuously adds text to the end

In my Angular application, I have implemented an input field with the onkeypress event handler to automatically remove any commas entered by the user: <input name="option" ng-model="main.optionToAdd" onkeypress="this.value = this.value.replace(/,/g ...

What is the best way to track upload progress while using Django?

Is it possible to implement an upload progress bar for a website using Django? I'm interested in tracking the progress of file or image uploads but unsure how to accomplish this. Any tips on retrieving the upload status? ...

Symfony2: Making AJAX request that unexpectedly returns complete html page

I am facing an issue with setting up a basic AJAX request in Symfony2. It appears that the controller is not receiving the request as expected. Instead of displaying '123', the AJAX response shows the HTML content of the current page (index.html. ...

What is the best method for extracting specific JSON response elements and appending them to an array?

I've been utilizing the Nomics cryptocurrency API in my project. Below is an example of the Axios call: axios.get(apiURL + apiKey + apiSpecs) .then(function (response) { // sort data by highest market cap console.log(response.data) }) Here' ...

Submitting a form using jQuery and processing the response

Can a form be submitted using jQuery without utilizing json, ajax, or other methods for handling the result? For example: <form id="loginform"> //some input fields and a submit button. </form> And then with jQuery: $("#loginform").sub ...

How can I locate a single hidden field within a div containing multiple fields?

Within one div, I have three hidden fields. How can I access and retrieve just one of these hidden fields when referencing this specific div? ...

Creating a Vue.js modal with dynamically generated IDs: A step-by-step guide

Just getting started with VueJS and feeling a bit overwhelmed. I'm working on a table that takes an array of objects and generates each row for display. Each row should have a button, and when the button is clicked, a modal should pop up with specifi ...

A guide on efficiently deserializing the JSON response from an API using C#

Is there a way to create models from the JSON data, particularly if the data includes a string keyword name? The JSON Data: { "Meta Data": { "1. Information": "Intraday (5min) open, high, low, close prices and volume&q ...