假设我有一个Reusable的组件onClick方法设置数据道具。 我希望这个组件可以重用,我想使用插槽来覆盖部件。
据我所知,我必须将onClick方法作为scoped属性传递给reusable parent :
<div class="reusable"> <h2>Reusable</h2> <slot name="clicker" v-bind:onClick="onClick"> Default stuff <button v-on:click="onClick">Close</button> </slot> <p v-if="clicked">You clicked me</p> </div> <div class="parent"> <h1>Parent</h1> <reusable> <template slot="clicker" scope="reusable"> <button click="reusable.onClick"> Close from parent </button> </template> </reusable> </div>如果我有很多方法,这可能会变得冗长和嘈杂,我想知道: 有更好的方法 ,还是这完全是cromulent?
我已经看过使用refs,并且在父级上调用了this.$refs.reusable.onClick ,以及指定动态组件并将它们交换出去; 两者似乎都违反直觉。
Say I have a component Reusable with a method onClick that sets a data prop. I want this component to be reusable, and I want to use slots to override parts.
As I understand the canon, I must pass the onClick method as a scoped property up to parent from reusable:
<div class="reusable"> <h2>Reusable</h2> <slot name="clicker" v-bind:onClick="onClick"> Default stuff <button v-on:click="onClick">Close</button> </slot> <p v-if="clicked">You clicked me</p> </div> <div class="parent"> <h1>Parent</h1> <reusable> <template slot="clicker" scope="reusable"> <button click="reusable.onClick"> Close from parent </button> </template> </reusable> </div>This might get verbose and noisy if I have a lot of methods, and I wondered: is there a better way, or is this entirely cromulent?
I've looked at using refs, and having methods on the parent call this.$refs.reusable.onClick, as well as specifying dynamic components and swapping them out; both seem counterintuitive.
最满意答案
您可以使用对象表示法绑定插槽的属性:
<slot name="clicker" v-bind="{ onClick, onInput, onCustom }"> Default stuff <button v-on:click="onClick">Close</button> </slot>这是一个工作小提琴。
如果它变得过于冗长,您至少可以将对象定义移动到数据属性并将其从模板中取出:
<slot name="clicker" v-bind="scopeProps"> Default stuff <button v-on:click="onClick">Close</button> </slot>data() { return { scopeProps: { onClick: this.onClick, onInput: this.onInput, onCustom: this.onCustom } } }You could bind the slot's properties using object notation:
<slot name="clicker" v-bind="{ onClick, onInput, onCustom }"> Default stuff <button v-on:click="onClick">Close</button> </slot>Here's a working fiddle.
And if that gets to be too verbose you could at least move the object definition to the data properties and get it out of the template:
<slot name="clicker" v-bind="scopeProps"> Default stuff <button v-on:click="onClick">Close</button> </slot>data() { return { scopeProps: { onClick: this.onClick, onInput: this.onInput, onCustom: this.onCustom } } }
更多推荐
发布评论