I am using Vue 3 . I am unable to get dataset values from my button:
this is the button:
<script src="https://unpkg.com/vue@3.4.9/dist/vue.global.js"></script>
<button id="profile"
v-on:click="start" :data-id="19876"
class="profile"
data-gender="{{$gender}}">
</button>
This is my vue object:
<script>
Vue.createApp({
data() {
return {
state: null,
};
},
mounted() {
console.log(this);
},
methods: {
startChat(event){
// const { id } = event.target.dataset;
var id = event.target.getAttribute('data-id');
console.log(id);
},
}
}).mount('#profile');
</script>
This return the value null.
I also tried this:
const { id } = event.target.dataset;
It return value undefined.
You're mounting Vue directly on the #profile
button, but Vue works best when mounted on a wrapper element (for example a <div>
) that contains the button. Since the button itself is the root of the Vue instance, Vue takes over and removes the data-* attributes, which is why you're not getting the expected values.
To fix it, wrap your button inside a and mount Vue on that div instead.
<script src="https://unpkg.com/vue@3.4.9/dist/vue.global.js"></script>
<div id="app">
<button id="profile"
v-on:click="startChat"
:data-id="19876"
class="profile"
data-gender="male">
Click Me
</button>
</div>
<script>
Vue.createApp({
methods: {
startChat(event){
// const { id } = event.target.dataset;
var id = event.target.getAttribute('data-id');
console.log(id);
},
}
}).mount('#app'); // Mount Vue here
</script>
Read more about mounting Vue on the official docs