[英]Component can't call a method from the Vue instance v-on:click
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.我是 Vuejs 的新手,我只想从我的 Vue 实例中调用一个方法,但这似乎是一个问题,我不知道为什么。
Vue instance: Vue 实例:
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.我想用组件中声明的按钮用我的怪物的 ID 调用 deleteMonster() 方法。
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)
You need to emit
an event to the parent component monsterlist
which calls its deleteMonster
function passing the custom id
as follows:您需要向调用其deleteMonster
function 传递自定义id
的父组件monsterlist
emit
一个事件,如下所示:
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>
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.