Basically I want to create an object that holds all the backend api urls.
backendUrls: {
pathParts: {
house: '/house',
office: '/office'
},
baseUrl: 'http://localhost:8080',
houseUrl: this.baseUrl + this.pathParts.house
}
But when I start the project (it is VueJS if its important) and I want to open the page the console says: TypeError: Cannot read properties of undefined (reading 'house')
.
Thanks in advance.
2
Answers
You can reference other properties of the same object when defining a new property if you make it a method. Here’s an example:
If we make the
houseUrl
property a getter method, it can be accessed like a regular property without the need to call it as a function.Here’s an updated version of the
backendUrls
object withhouseUrl
as a getter method:Now we can access the
houseUrl
andofficeUrl
properties as follows:Note that we call
houseUrl
andofficeUrl
as if they were regular properties, without using parentheses to indicate a function call. This is because they are now defined as getter methods.The
baseUrl
andpathParts
do not exist at the instant that you are creatinghouseUrl
.They all start existing at effectively the same time, so they can’t reference each other.
If you want one variable to depend on another, you need it to be created later. Try creating
houseUrl
in a computed property. Inside a computed property you are free to access items initialised indata()
.