I am using regular Vue.js in my project. I store data in a store made from scratch and use it in a template:
<template> <div> <div class="row"> <div v-for="(picture, index) in storeState.pictures" :key="index" class="col-md-2 my-auto"> <div > <img class="img-thumbnail img-responsive" :src="picture.url" @click="deleteMe"> </div> </div> </div> </div> </template> <script> import { store } from "../common/store.js" export default { name:"PictureUpload", data() { return { storeState: store.state, }; }, methods: { deleteMe() { let apiUrl = this.picture.url console.log(apiUrl) } } } </script>
My pictures are rendering well but now I want to add a delete()
function to the picture @click
and whenever I click on the button I get:
TypeError: Cannot read property 'url' of undefined
So how can I access my picture data inside my method?
Advertisement
Answer
You should pass picture
as parameter in the click handler :
@click="deleteMe(picture)">
and refer to it in the method like :
methods: { deleteMe(picture) { let apiUrl = picture.url //omit this console.log(apiUrl) } }
the storeState
should be a computed property :
export default { name:"PictureUpload", data() { return { }; }, computed:{ storeState(){ return store.state; } }, methods: { deleteMe(picture) { let apiUrl = picture.url console.log(apiUrl) } } }