如何在 Vue.js 插槽范围内传递方法 [英] How to pass a method in Vue.js slot scope
问题描述
我在 vuejs 中使用了一个槽作用域.它工作得很好.我可以像这样将任何我想要的东西传递到插槽中:
</slot>
问题是当我将一个函数作为 prop 传递时,它在父模板中是未定义的.所以这不起作用:
</slot>
在这个例子中,myMethod 是一个定义在子 vue 组件上的方法.(我用的是打字稿,所以它是组件类上的一个方法)
关于如何将在子组件上定义的函数通过插槽道具传递回父组件以便可以从父组件的插槽代码中调用它的任何想法?
UPDATE
此答案是为较旧的pre v2.6 语法编写的.从那时起,此语法已被标记为弃用.核心功能保持不变,函数(方法)的工作方式与向上绑定的属性(从子级到父级)相同,但是定义现在使用 v-slot:default
.
根据更新的文档(
<小时>使用 pre v2.6 语法的原始答案.如何传递 slot-scope
父母:
<div slot="item" slot-scope="{ myLink, myMethod }"><button @click="myMethod(myLink.title)">书签按钮>
</模板>
孩子:
<li v-for="链接中的myLink"><slot name="myLink" :myLink="myLink" :myMethod="myMethod"></slot></模板><脚本>导出默认{方法: {我的方法(链接){link.bookmarked = true}}}
I'm using a slot scope in vuejs. It's working great. I can pass anything I want into the slot like this:
<slot :item1="item1">
</slot>
The problem is that when I pass a function as a prop, it is undefined in the parent template. So this doesn't work:
<slot :my-method="myMethod">
</slot>
In this example, myMethod is a method defined on the child vue component. (I am using typescript, so it is a method on the component class)
Any ideas on how to pass a function defined on the child component back through the slot props to the parent so that it can be called from within the slot code in the parent?
UPDATE
This answer was written for the older pre v2.6 syntax. Since then, this syntax has been marked for deprecation. The core functionality stays the same, the functions(methods) work the same way as the properties that are being bound upwards (from child to parent), however the definition uses v-slot:default
now.
as per updated documentation (https://vuejs.org/v2/guide/components-slots.html#Scoped-Slots),
<span> <slot v-bind:user="user"> {{ user.lastName }} </slot> </span>
Attributes bound to a element are called slot props. Now, in the parent scope, we can use v-slot with a value to define a name for the slot props we’ve been provided:
<current-user> <template v-slot:default="slotProps"> {{ slotProps.user.firstName }} </template> </current-user>
Here is a more complicated example, as you will notice, the function and the scoped slots are passed using slotProps
Original answer with pre v2.6 syntax. Example of how to pass the slot-scope
parent:
<template>
<div slot="item" slot-scope="{ myLink, myMethod }">
<button @click="myMethod(myLink.title)">
Bookmark
</button>
</div>
</template>
child:
<template>
<li v-for="myLink in links">
<slot name="myLink" :myLink="myLink" :myMethod="myMethod"></slot>
</li>
</template>
<script>
export default {
methods: {
myMethod(link) {
link.bookmarked = true
}
}
}
</script>
这篇关于如何在 Vue.js 插槽范围内传递方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!