Reputation: 55
I'm pretty new to Vuejs and I'd just like to call a methode from my Vue instance but it seems like this is a porblem and I don't know why.
Vue instance:
var monster = new Vue({
el: '#monsterlist',
data: {
monsters: undefined
},
created: async function (){
this.monsters = await this.loadMonster()
},
methods: {
loadMonster: async function () {
//stuff
},
deleteMonster: async function(id){
//stuff
}
}
})
Component:
Vue.component('monster', {
template: '<div class="content overlayable"> <div class="overlay" v-if="monster.deleting"><div class="lds-ripple"><div></div><div></div></div></div> <div><h1>{{monster.name}}</h1> <div class="static"> <div class="des"><img v-if="monster.image != undefined && monster.image != ``" :src="monster.image"> <a v-else>No monster image</a></div> <button class="denyBtn" v-on:click="deleteMonster(monster._id)">Delete</button> </div></div> </div>',
props: ['monster']
})
I'd like to call the deleteMonster() methode with the id of my monster with a button declared in the component.
Here is the error I'm getting:
vue@2:6 ReferenceError: deleteMonster is not defined
at click (eval at Ya (vue@2:6), <anonymous>:3:451)
at He (vue@2:6)
at HTMLButtonElement.n (vue@2:6)
at HTMLButtonElement.Yr.o._wrapper (vue@2:6)
Upvotes: 2
Views: 638
Reputation: 28404
You need to emit
an event to the parent component monsterlist
which calls its deleteMonster
function passing the custom id
as follows:
const monster = Vue.component('monster', {
template: '#monster',
props: ['monster']
})
new Vue({
el: '#monsterlist',
components: { monster },
data: {
monsters: undefined
},
created: async function (){
this.monsters = await this.loadMonster()
},
methods: {
loadMonster: async function () {
return [
{_id:1},
{_id:2},
];
},
deleteMonster: async function(id){
console.log(id);
}
}
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.17/vue.js"></script>
<div id="monsterlist">
<monster
v-for="(monster,index) in monsters"
:key="index"
:monster="monster"
@delete="deleteMonster"
/>
</div>
<template id="monster">
<div class="content overlayable">
<div class="overlay" v-if="monster.deleting">
<div class="lds-ripple">
<div></div>
<div></div>
</div>
</div>
<div>
<h1>{{monster.name}}</h1>
<div class="static">
<div class="des">
<img v-if="monster.image != undefined && monster.image != ``" :src="monster.image">
<a v-else>No monster image</a>
</div>
<button
class="denyBtn"
v-on:click="$emit('delete',monster._id)"
>Delete</button>
</div>
</div>
</div>
</template>
Upvotes: 2