如何在组件 vue.js 内的标签中发出事件
Posted
技术标签:
【中文标题】如何在组件 vue.js 内的标签中发出事件【英文标题】:How can I emit event in a tag inside the component vue.js 【发布时间】:2021-11-29 19:09:00 【问题描述】:main.js
Vue.component("modal",
template : /*html*/`
<div class="modal is-active" >
<div class="modal-background"></div>
<div class="modal-card">
<header class="modal-card-head">
<p class="modal-card-title">
<slot name="header"></slot>
</p>
<button class="delete" aria-label="close" @click="$emit('close')"></button>
</header>
<section class="modal-card-body">
<slot></slot>
</section>
<footer class="modal-card-foot">
<slot name="footer">
</slot>
</footer>
</div>
</div>
`
);
new Vue(
el:'#root',
data :
isActive : false
,
);
index.html
<modal v-if="isActive" @close =" isActive = false">
<template slot="header"> Title</template>
some thing...
<div slot="footer">
<button class="button is-success">Save changes</button>
<button class="button" @close="isActive = false">Cancel</button>
</div>
</modal>
组件内部的按钮工作正常,问题出在外部的另一个按钮上。
太简单了,我想要这个按钮“在模式内”<button class="button" @close="isActive = false">Cancel</button>
关闭它的模态:) 谢谢!
【问题讨论】:
该按钮内的任何内容都不会发出 close 事件。使用@click
而不是@close
【参考方案1】:
您只能像在此处 <modal v-if="isActive" @close="isActive=false">
那样在组件上收听事件 @close
。在组件内的按钮处,您可以使用@click="isActive=false"
Vue.component("modal",
template : `
<div class="modal is-active" >
<div class="modal-background"></div>
<div class="modal-card">
<header class="modal-card-head">
<p class="modal-card-title">
<slot name="header"></slot>
</p>
<button class="delete" aria-label="close" @click="$emit('close')"></button>
</header>
<section class="modal-card-body">
<slot></slot>
</section>
<footer class="modal-card-foot">
<slot name="footer">
</slot>
</footer>
</div>
</div>`
);
new Vue(
el:'#root',
data :
isActive : false
,
);
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.17/vue.js"></script>
<div id="root">
<button @click="isActive = true">open</button>
<modal v-if="isActive" @close="isActive = false">
<template slot="header"> Title</template>
some thing...
<div slot="footer">
<button class="button is-success">Save changes</button>
<button class="button" @click="isActive = false">Cancel</button>
</div>
</modal>
</div>
【讨论】:
以上是关于如何在组件 vue.js 内的标签中发出事件的主要内容,如果未能解决你的问题,请参考以下文章