When it comes to defining data in a Vue component, the typical approach is to use the data function as shown below:
data()
{
return {
a: 0
}
}
But I have a question: instead of defining the data object after return
, is it possible to define the data object elsewhere and simply create an instance of it in the data
function?
For example:
Within the Vue component:
data()
{
return new DataObject();
}
And then in a separate file, say DataObject.js:
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;
}
}
}
Unfortunately, this approach does not work. I did come up with a workaround that allows me to achieve this:
data()
{
return {
data: new DataObject();
}
}
While this workaround is effective, it still involves defining a wrapper data object in order to use the data object, and accessing a
as this.data.a
instead of just this.a
.
So my question is: is it feasible to implement this in my desired way without defining the data or wrapper data object inside the data
function?
I want to be able to return an external data object directly from the data
function.