Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

274
Views
How to use external object in Vue's data() function?

So, the stadard way of defining data in Vue component is by using the data function like in the following example:

data()
{
    return {
        a:0
    }
}

My question is, instead of defining the data object after return, can I define the data object somewhere else and just create its instance in data function?

So, for example:

Inside Vue component:

data()
{
    return new DataObject();
}

and then in DataObject.js do:

class DataObject
{
    constructor(a)
    {
        this._a = a;
    }
    get a()
    {
        return this._a;
    }
    set a(a)
    {
        if (a > 0)
        {
            this._a = a;
        }
        else
        {
            this._a = 0;
        }
    }
}

This does not work. I created the following workaround which enables me to do this:

data()
{
    return {
        data: new DataObject();
    }
}

and this works as expected, but I still define the wrapper data object in order to be able to use data object and I have to access the a as this.data.a instead of just this.a.

So, is it possible to implement this on my way, without defining the data nor wrapper data object inside the data function?

So I want to be able to return external data object from the data function.

about 4 years ago · Juan Pablo Isaza
2 answers
Answer question

0

It's fine to construct the object outside of the data prop. The problem with the OP code is the DataObject's getters. vue will replace those with reactive get/set, deleting the knowledge of the underlying variable.

class SomeClass {
  constructor() {
    this.a = 'A';
    this.b = 'B';
    this.c = 'C';
  }
  // get a() will be overwritten
}

window.onload = () => {
  new Vue({
    el: '#app',
    data: function() {
      return new SomeClass()
    },
  })
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.17/vue.js"></script>
<div id="app">
  <h3>{{a}}</h3>
  <h3>{{b}}</h3>
  <h3>{{c}}</h3>
</div>

about 4 years ago · Juan Pablo Isaza Report

0

you are not providing a name to the object you are trying to create

return new DataObject();

try instantiating the class somewhere in your code first and then return it

let instance = new DataObject();  
return instance;
about 4 years ago · Juan Pablo Isaza Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!