data in app.component instance is not reactive if data is declared inside data() or setup() | VueJS 3

I want to declare new reactive variables inside a component. Setting the component globally (outside the app.component instance) and returning it to data() or setup() function works. But it doesn't work when I declare the reactive object inside data() or setup() event.

Here is the example code:

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();

editing values in editEducationData works but not in this even inside the instance (please refer to methods on the above code).

What is the possible solution to this problem?

Upvotes: 0

Views: 49

Answers (1)

Boussadjra Brahim
Boussadjra Brahim

Reputation: 1

Using composition and Options APIs in the same component with interchanging data is bad practice and it makes your component inconsistent, It's recommended to use one API based on the 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>`
});

Upvotes: 1

Related Questions