英文:
How to pass event listener to the root component?
问题
我正在使用Vue 3,并且我知道在使用组件时,你可以使用v-on指令传递监听器回调函数,也可以使用其简写形式**@**(就像下面的示例中一样)。
<my component @click="myCallback"/>
但是否有一种方法可以将它们传递给应用程序(根组件)?
import { createApp } from 'vue'
// 从单文件组件中导入根组件App。
import MyComponent from './MyComponent.vue'
const app = createApp(MyComponent, {props})
英文:
I am using vue3 and I know that when working with components you can pass listener callbacks using v-on directive or use its shorthand @ (like in the example below).
<my component @click="myCallback"/>
But is there a way to pass them to the app (root component)?
import { createApp } from 'vue'
// import the root component App from a single-file component.
import MyComponent from './MyComponent.vue'
const app = createApp(MyComponent, {props})
答案1
得分: 2
v-on-*
模板语法被翻译为 h
函数 中的 on*
属性,用于创建虚拟节点。考虑到 MyComponent
发出 foo
事件,代码如下:
const app = createApp(MyComponent, { onFoo() {...} })
英文:
v-on-*
template syntax is translated to on*
props in h
function, which is used to create vnodes. Considering that MyComponent
emits foo
event, it's:
const app = createApp(MyComponent, { onFoo() {...} })
答案2
得分: 2
你没有将回调传递给组件,而是对它们触发的事件做出反应。如果你想在Vue的“根应用程序”中对某个事件做出反应,只需在根模板中定义v-on
。
所以,对于你的示例:
如果你将组件放入应用程序模板并将回调定义为应用程序方法,那么当事件发生时将调用你的方法。
应用程序:
<template>
<my-component @click="myCallback"/>
</template>
和
methods: {
myCallback(event) {
....
}
}
示例:
<div id="app" v-cloak>
<my-comp @click="myCallback"></my-comp>
</div>
<script src="https://unpkg.com/vue@3/dist/vue.global.prod.js"></script>
英文:
You are not passing callbacks to the components, but reacting to events from them. If you want to react on some event in the Vue root app
, then just define v-on
s in the root template.
So, for your example:
If you put your component into the app template and define the callback as app method, then your method will be called when the event occurs.
App
<template>
<my component @click="myCallback"/>
</template>
and
methods: {
myCallback(event) {
....
}
}
Example
<!-- begin snippet: js hide: false console: true babel: false -->
<!-- language: lang-js -->
const MyComp = {
emits: ['click'],
template: `<button id="my-button" @click="$emit('click', $event)">Click me!</button>`
}
const App = {
components: { MyComp },
methods: {
myCallback(event){
alert('Clicked button: ' + event.target.id)
}
}
}
Vue.createApp(App).mount('#app')
<!-- language: lang-css -->
#app { line-height: 1.75; }
[v-cloak] { display: none; }
<!-- language: lang-html -->
<div id="app" v-cloak>
<my-comp @click="myCallback"></my-comp>
</div>
<script src="https://unpkg.com/vue@3/dist/vue.global.prod.js"></script>
<!-- end snippet -->
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论