【问题标题】:Access and declare vueJs component inside other component slot在其他组件槽内访问和声明 vueJs 组件
【发布时间】:2021-11-17 18:41:03
【问题描述】:

我正在尝试在组件槽内声明和访问一个 vue 组件。 模态组件将被创建多次,并且它必须有一个唯一的名称,但我不知道我是如何在插槽内做到这一点的。 使用 Laravel Blade 和 vueJs

<template>
    <table>
        <thead>
            <slot name="head"/>
        </thead>
        <tbody>
        <tr v-for="item in items" :key="item.id">
            <slot name="line" v-bind:item="item" />
        </tr>
        </tbody>
    </table>
</template>
<list-component ref="teamMembers">
    <template v-slot:head>
        <tr>
            <th>Name</th>
            <th>Email-address</th>
            <th>Role</th>
        </tr>
    </template>


    <template v-slot:line="slotProps">
        <td>
            @{{ slotProps.item.name }}
        </td>
        <td>
            @{{ slotProps.item.email }}
        </td>
        <td>
            @{{ slotProps.item.role }}
        </td>

        <td>
            <button @click="$refs.deleteItemModal@{{ slotProps.item.id }}">
                Delete
            </button>
        </td>

        <modal-component ref="deleteItemModal@{{ slotProps.item.id }}">
            
        </modal-component>
    </template>
</list-component>

模态组件如何声明和调用?

如果我这样使用它

<button @click="$refs.deleteItemModal">

ref="deleteItemModal"

它可以工作,但总是给我相同的组件。

请告诉我如何创建一个独特的 ref 来创建类似 'deleteItemModal' + slotProps.item.id 的东西

【问题讨论】:

    标签: vue.js vuejs2 vue-component laravel-blade


    【解决方案1】:

    你可以这样试试:

    <modal-component :ref="'deleteItemModal' + slotProps.item.id">
    </modal-component>
    

    静态值应该用引号覆盖,并且可以使用+将任何动态值与javascript中的字符串连接起来。

    要调用该引用组件的openModal 方法,请在modal-component 组件中创建方法

    deleteItem(itemId) { this.$refs['deleteItemModal' + itemId].openModal() }
    

    然后更改为按钮点击事件

    <button @click="deleteItem(slotProps.item.id)">
    

    【讨论】:

    • 感谢您的回答,但我应该如何声明点击 @click="'$refs.deleteItemModal' + slotProps.item.id + '.openModal()'" 因为这不起作用。
    • 您需要创建一个方法,并且您可以将您想要的相应代码作为动态代码执行。并在点击中调用该方法
    • 方法在“openModal”中准备就绪。但我无法引用它。
    • 好的,但我的意思是在modal-component 组件中创建方法并在其中调用引用组件的openModal() 方法。即deleteItem(itemId) { this.$refs['deleteItemModal' + itemId].openModal() },然后更改为按钮单击事件&lt;button @click="deleteItem(slotProps.item.id)"&gt;
    • 感谢 Urja,现在我可以使用它了。
    猜你喜欢
    • 2018-03-02
    • 2020-09-16
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-04-25
    • 1970-01-01
    • 2020-04-21
    • 1970-01-01
    相关资源
    最近更新 更多