简体   繁体   中英

Access data from a vue array element when it is clicked

My vue data consists of a list of people.

self.vue = new Vue({
    el: "#vue-div",
    delimiters: ['${', '}'],
    unsafeDelimiters: ['!{', '}'],
    data: {
        users: [
            {first_name: "John",
             last_name: "Doe",
             email: "jdoe@gmail.com"
            },
            {first_name: "Jane",
             last_name: "Smith",
             email: "jsmith@gmail.com"
            },
        ]
    },
    methods: {
        test: function(e) {
            alert(this.users[0].email);

        }
    }

});

I then display the names of those people in a list using v-for:

<ul v-for="user in users">
    <li class="btn btn-primary" v-on:click="test">${user.first_name} ${user.last_name}</li>
</ul>

currently, in order to alert the actual email of a user in the array, I have to hardcode an index to be alerted. My question is, how do I dynamically access the data of the array element that has been clicked on?

The solution I used was to get the index while rendering the array elements, and then passing that index to a function.

I could then look up the element in the array and alert the email

<ul v-for="(user, index) in users">
    <li v-on:click="test(index)">${user.first_name} ${user.last_name}</li>
</ul>

self.test = function(index) {
   alert(self.vue.users[index].email);
}

You can simply pass the email to the test function in the template:

v-on:click="test(user.email)"

And then:

function test(email) {
    alert(email);
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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