Reputation: 328
I'm fairly new to Vue Js and I'm trying to access a property (containing a boolean) in an array from a method so I can change the boolean on a button click but I'm not sure how to access it.
export default {
name: 'app',
data() {
return {
leftImg: [
{
english: 'School',
welsh: 'Ysgol',
id: 'school',
url: require('./img/school.jpg'),
tag: 'left',
displayEnglish: true,
},
methods: {
changeEnglish () {
this.leftImg.displayEnglish = false //This doesn't work
},
}
Upvotes: 0
Views: 513
Reputation: 233
leftImg
is an array. You cannot assign a value of an array element directly, so before assigning the value you should index it.
to change the first item of the array, you can use something like,
this.leftImg[0].displayEnglish = false
But, if you are having only one item in the array, better make the leftImg
as Object. like:
data() {
return {
leftImg:
{
english: 'School',
welsh: 'Ysgol',
id: 'school',
url: require('./img/school.jpg'),
tag: 'left',
displayEnglish: true
}
}
}
Make the changes according to your use cases. :)
Upvotes: 0
Reputation: 16364
You have multiple problems on the code you provided. First of all, make sure to have a correct javascript syntax. Just from your syntax, your code would look like this:
export default {
name: 'app',
data() {
return {
leftImg: [
{
english: 'School',
welsh: 'Ysgol',
id: 'school',
url: require('./img/school.jpg'),
tag: 'left',
displayEnglish: true,
}
]
}
},
methods: {
changeEnglish() {
this.leftImg.displayEnglish = false //This doesn't work
},
}
}
Secondly, as you said in your question, the leftImg
property is an array. So you should make sure that you specify on which index of this array you wish to update the displayEnglish
property. In case you would like to update the first item of your array, you would have to write:
this.leftImg[0].displayEnglish = false
If it's the second, you should write
this.leftImg[1].displayEnglish = false
And so on...
Upvotes: 1