0

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: "[email protected]"
            },
            {first_name: "Jane",
             last_name: "Smith",
             email: "[email protected]"
            },
        ]
    },
    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?

2 Answers 2

1

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);
}
Sign up to request clarification or add additional context in comments.

Comments

0

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);
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.