我在 vuejs 中使用插槽范围。效果很好。我可以将任何我想要的东西传递到插槽中,如下所示:
<slot :item1="item1">
</slot>
问题是,当我将函数作为 prop 传递时,它在父模板中未定义。所以这不起作用:
<slot :my-method="myMethod">
</slot>
在此示例中,myMethod 是在子 vue 组件上定义的方法。 (我使用的是打字稿,所以它是组件类上的一个方法)
关于如何将子组件上定义的函数通过插槽属性传递回父组件,以便可以从父组件的插槽代码中调用它,有什么想法吗?
UPDATE
这个答案是写给长辈的pre v2.6句法。从那时起,此语法已被标记为弃用。核心功能保持不变,函数(方法)的工作方式与向上绑定(从子级到父级)的属性相同,但是定义使用v-slot:default
now.
根据更新的文档(https://v2.vuejs.org/v2/guide/components-slots.html#Scoped-Slots https://v2.vuejs.org/v2/guide/components-slots.html#Scoped-Slots),
<span>
<slot v-bind:user="user">
{{ user.lastName }}
</slot>
</span>
绑定到元素的属性称为槽属性。现在,在父作用域中,我们可以使用 v-slot 和一个值来为我们提供的插槽属性定义名称:
<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
原始答案与pre v2.6句法。如何通过的示例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>
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)