函数作为组件道具的问题 [英] Issue with functions as props for components
问题描述
我有一种在整个应用程序中使用的按钮类型,例如:<button type="button" class="btn btn-default" @click.prevent="search">搜索按钮>
.虽然代码字符的节省很小,但我觉得为此创建一个小组件 Btn 是值得的.我可以这样使用它:<btn :action="search">Search</btn>
.一切都很好.
I have a type of button I use throughout my application, an example of which is this: <button type="button" class="btn btn-default" @click.prevent="search">Search</button>
. Although the savings in code characters are small, it struck me as worthwhile to create a little component for this, Btn. I could use this thus: <btn :action="search">Search</btn>
. All well and good.
但是当我想使用 Vue 的内部特殊变量之一作为函数中的参数时遇到了问题.例如,
.'removeSelected' 函数需要将事件作为第二个参数传递.但是,它作为组件中作为道具传递的函数中的参数无效.我收到错误消息:[Vue 警告]:属性或方法$event"未在实例上定义,但在渲染过程中被引用."有没有办法解决这个问题?
But I have a problem when I want to use one of Vue's internal special variables as an argument in the function. For example, <btn :action="removeSelected(index,$event)">X</btn>
. The 'removeSelected' function needs to be passed the event as the second parameter. It's not valid as an argument in the function passed as a prop in a component, though. I get the error message: "[Vue warn]: Property or method "$event" is not defined on the instance but referenced during render." Is there any way round this?
推荐答案
这里的主要问题是您想将一个函数传递给将接收 $event
参数(所有事件处理程序默认接收)以及传递在父级中定义的参数.为此,您可以在 action
参数本身内定义一个函数.
The main issue here is that you want to pass a function to the child component that will receive the $event
parameter (which all event handlers receive by default) as well as passing a parameter defined in the parent. In order to do that, you can define a function inside the action
parameter itself.
:action="($event) => removeSelected(index, $event)"
这定义了一个接收 $event
作为参数的函数,该函数使用捕获索引调用 removeSelected
方法并传递事件.
This defines a function that receives $event
as a parameter that calles the removeSelected
method with the capture index and passes along the event.
工作示例.
这篇关于函数作为组件道具的问题的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!