gpt4 book ai didi

javascript - 组件无法从 Vue 实例 v-on :click 调用方法

转载 作者:行者123 更新时间:2023-12-04 08:15:11 25 4
gpt4 key购买 nike

我对 Vuejs 很陌生,我只想从我的 Vue 实例中调用一个方法,但这似乎是一个问题,我不知道为什么。
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
}
}
})
成分:
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']
})
我想使用我的怪物的 id 调用 deleteMonster() 方法,并在组件中声明一个按钮。
这是我得到的错误:
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)

最佳答案

您需要emit父组件的事件 monsterlist调用它的 deleteMonster传递自定义的函数 id如下:

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>

关于javascript - 组件无法从 Vue 实例 v-on :click 调用方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/65743196/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com