I’ve struggled with an issue that seems really silly, but I could not find a solution for it.
The following variable declaration works:
export default {
data() {
return {
random_number: 1,
random_array: ['A','B','C'],
}
}
However, if I try to declare a third variable that accesses random_array, as in the two examples below, it doesn’t work:
export default {
data() {
return {
random_number: 1,
random_array: ['A','B','C'],
random_var: random_array[1],
}
}
export default {
data() {
return {
random_number: 1,
random_array: ['A','B','C'],
random_var: random_array[random_number],
}
}
I have tried referencing the arrays as this.random_array[1] or this.random_array[this.random_number], but neither have worked.
It seems like a simple syntax issue, but I couldn’t figure it out or find the solution online.
>Solution :
You can’t refer to an object within this same object. It’s like doing this:
const myObj = {
firstName: 'Micheal',
lastName: 'Scott',
name: firstName + lastName, // these variables doesn't exist
// or even
name: myObj.firstName + myObj.lastName, // the myObj variable isn't created yet, you can't access it from itself
}
Your solution is simply to put your values inside variables before doing the return:
data() {
const myNumber = 1;
const myArray = ['A','B','C'];
return {
random_number: myNumber,
random_array: myArray,
random_var: myArray[myNumber],
}
}
Note: if you name your variable with the same name as the object attribute, you can use shorthand property initalizer to shorten your code:
data() {
const random_number = 1;
const random_array = ['A','B','C'];
return {
random_number, // same as doing "random_number: random_number,"
random_array,
random_var: random_array[random_number],
}
}