Home > OS >  How to use external object in Vue's data() function?
How to use external object in Vue's data() function?

Time:05-12

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.

CodePudding user response:

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>

CodePudding user response:

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;
  • Related