In VueJS 3, the data within the app.component instance will lack reactivity if it is declared within the data() or setup() functions

When it comes to declaring new reactive variables inside a component, I faced an interesting issue. It seems that setting the component globally, outside the app.component instance, and then returning it to either the data() or setup() function works perfectly fine. However, when I try to declare the reactive object directly inside the data() or setup() event, it doesn't work as expected.

Let's take a look at an example code snippet:

const editEducationData = reactive({
      attainment: null,
      degree: null,
      yeargraduated: null
});

app.component("educationmodal", {
    setup() {
        // this is reactive...
        return editEducationData;

        // this is not reactive..
        return reactive({
              attainment: null,
              degree: null,
              yeargraduated: null
        });
    },
    methods: {
        setValues() {
            // this doesen't work....
            this.attainment = "value";

            // this works....
            editEducationData.attainment = "newvalue";
        },
        show() {

        }
    },
    template: 
    /* html */
    `<div>{{ attainment }}</div>`
});

/* this updates {{ attainment }} in template */
editEducationData.attainment = "new values";

/* this does not update {{ attainment }} in template but setValues method is firing  */
app.component("educationmodal").methods.setValues();

While editing values in editEducationData works flawlessly, attempting the same with this inside the instance leads to inconsistencies (as seen in the above code).

So, what could be the potential solution to overcome this challenge?

Answer №1

It is not a recommended practice to mix composition and Options APIs in the same component when dealing with interchangeable data. Doing so can lead to inconsistencies in your component. It's better to stick to one API that is based on reactive properties:

app.component("educationmodal", {
    setup() {
       
       const editEducationData = reactive({
              attainment: null,
              degree: null,
              yeargraduated: null
        });
    
     function setValues(){
            editEducationData.attainment = "newvalue";
     }


     return {
        editEducationData,
        setValues
    }

    },
  
    template: 
    /* html */
    `<div>{{ editEducationData.attainment }}</div>`
});

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

Why isn't the hover function working on the table row element?

When I try to apply a hover effect on tbody and td elements, it works perfectly. However, when I apply the same effect to the tr element, it doesn't work as expected. I am using inline style (js pattern) rather than CSS code and incorporating Radium i ...

What advantages come from destructuring in conjunction with require statements?

When utilizing require, is there a performance advantage or disadvantage to importing the entire module versus only importing selected functions? It's my understanding that when using require to import modules (as opposed to using import), compilers ...

Ajax is not able to trigger a POST request to a PHP form

My form is not posting for some unknown reason, despite everything else on my server functioning properly. Below is the code snippet in question: PHP <?php if(isset($_POST['field1']) && isset($_POST['field2'])) { $data ...

Showcasing Information Using AngularJS from a Json Array

My goal is to present data from a JSON array in a table using the code below. However, all the data is currently being shown in one row instead of each record appearing on separate rows with alternating colors - grey for even rows and white for odd rows. I ...

Issue with relative templateUrl in Angular 2 not resolving paths

As I embark on creating my first Angular 2 app, I'm faced with the task of setting my template in an HTML file using `templateUrl`. Currently, both the component.ts and view.html are stored in the same folder under src/ directory. Here's what I ...

The dimensions of the sprites within Three.js geometry

I am interested in creating an animation of sprites moving along a figure, particularly sprites that walk along the figure. An example of what I envision can be seen here: http://armsglobe.chromeexperiments.com/ I found some helpful information related t ...

attack using JavaScript, AJAX, and PHP from a remote location

One vulnerability of using Javascript is that it's a client-side language, making scripts accessible for reading and copying. Let's take a look at this code snippet as an example: <html> <head> <title>title</title> <s ...

When using vue-cli, it does not automatically generate the folder structure

Currently, I am using vue 3.5.1 on my Ubuntu system. Once I installed the latest version by running: npm install -g @vue/cli I proceeded to create a new project with the command: vue create appname However, I noticed that vue only generated two files w ...

I am attempting to load the ajax content into separate divs simultaneously

When I attempt to load the ajax into two separate divs, I notice that despite calling for data to be placed in two different divs within the ajax code, it all ends up in one div. <script>$(document).ready(function(){ $.ajax({ url: "http: ...

I encountered a TS error warning about a possible null value, despite already confirming that the value

In line 5 of the script, TypeScript raises an issue regarding the possibility of gameInstanceContext.gameInstance being null. Interestingly, this concern is not present in line 3. Given that I have verified its existence on line 1, it is perplexing as to w ...

Sending a nested route broadcast in VueJS 2

Here are the routes I am using: <script> routes = [ { path: '/', component: Home, children: [{ path: 'nested1', name: 'nested1', component: Nested1, }, { ...

Unlocking protection: Confirming password strength and security with password indicator and regular expressions for special characters in angular through directive

I have developed an app for password validation using an AngularJS directive. The requirements for the password include at least one special character, one capital letter, one number, and a minimum length of 8 characters. Additionally, I have included a pa ...

Utilizing Angular 9's inherent Ng directives to validate input components within child elements

In my current setup, I have a text control input component that serves as the input field for my form. This component is reused for various types of input data such as Name, Email, Password, etc. The component has been configured to accept properties like ...

JavaScript and Angular are used to define class level variables

Hello, I'm currently diving into Angular and have encountered an issue with a class level variable called moratoriumID in my component. I have a method that makes a POST request and assigns the returned number to moratoriumID. Everything seems to work ...

Trouble displaying AngularJS $scope.data in the HTML code

I'm experiencing an issue where the data received from a POST request is being logged in the console, but is not displaying on the HTML page. Despite having a controller set up, the {{user}} variable is not appearing on the HTML page. While I can se ...

Create an Android application using Node.js

While developing my mobile application, I am utilizing html5 with node.js to create a chat box for users connected on the same wireless network. However, I encounter an issue when coding on my desktop using node.js software. How can I overcome this challen ...

Accordion with searchable tabular layout

Can you search for a product within an accordion? I have 34 categories in my accordion, each with a table containing at least 10 rows. Each row has a column with an icon that stores the data of that row. Please note that I am not using jQuery tables. If ...

Uncovering unseen tags generated by JavaScript on a webpage using Python

I have THIS LINK page that contains javascript. To view the javascript, simply click on show details. How can I extract data from this URL source? Should I use re? Here is what I attempted with re: import urllib import re gdoc = urllib.urlopen('Tha ...

Sequelize.js keeps the previous value for linked tables

My objective is to update the product status within the Product table. Each product has a statusId, which is either "1" or "2". The default value for statusId is always set to "1" for all products and should switch to "2" when the route is accessed once (a ...

Updating the Ajax Url dynamically while scrolling

I am trying to update the Ajax URL dynamically, and here is my progress so far: var size=1; var from = 1; window.addEventListener('mousewheel', function(e){ if(e.wheelDelta<0 && from<5){ from++; } else if(e.whe ...