简体   繁体   English

如何从Vue js中的方法访问数组中的属性?

[英]How do I access a property within an array from a method in Vue js?

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. 我是Vue Js的新手,我正尝试从方法访问数组中的属性(包含布尔值),因此可以在单击按钮时更改布尔值,但是我不确定如何访问它。

 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 }, } 

You have multiple problems on the code you provided. 您提供的代码有多个问题。 First of all, make sure to have a correct javascript syntax. 首先,请确保具有正确的javascript语法。 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. 其次,正如您在问题中所说的, leftImg属性是一个数组。 So you should make sure that you specify on which index of this array you wish to update the displayEnglish property. 因此,您应该确保指定要在此数组的哪个索引上更新displayEnglish属性。 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... 等等...

leftImg is an array. leftImg是一个数组。 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. 但是,如果数组中只有一项,最好将leftImg为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. 根据您的用例进行更改。 :) :)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM