Pankaj
Pankaj

Reputation: 10095

trying to retrieve element data attribute from vue.js component in Laravel

Component

<template lang="html">
    <div>
        <ul>
            <li @click="GetUser(this);" v-for="chatuser in chatusers" v-bind:data_id="chatuser.User_ID">
            </li>
        </ul>
    </div>
</template>
<script>

    export default {
        methods: {
            GetUser(id) {
                debugger;
                var data_id = $(id)[0].attr("data-id");
            }
        }
    }
</script>
<style>

</style>

Problem

In the Li, on click event, there is a function GetUser() with this argument passed. This element has data-id attribute which I am trying to retrieve in the function.

Problem is that, the data_id variable in the function is always undefined and when I debug the js code, it shows id value = Window.

Am I missing anything?

Upvotes: 0

Views: 5575

Answers (1)

Jacob Goh
Jacob Goh

Reputation: 20855

you may use $event. And get the data attribute from $event.target.dataset

And for html attributes, the standard is to use - instead of _

<li @click="GetUser($event);" v-for="chatuser in chatusers" v-bind:data-id="chatuser.User_ID">

export default {
    methods: {
        GetUser(e) {
            var data_id = e.target.dataset.id;
        }
    }
}

demo: https://codepen.io/jacobgoh101/pen/NyveNy

Upvotes: 3

Related Questions