Vue Draggable无法获取列表属性:无法显示title属性求助
问题与解决方法
有人能帮我找出这个简单示例中的错误吗?我想要显示title属性,但我大概误解了文档内容。是否需要设置特定属性才能获取到title属性?
用户提供的代码示例:
<template> <div id="app"> <draggable :list="cards" group="cards" itemKey="id"> <template #item="{card }"> <div class="card"> <h2>{{ card.title }}</h2> </div> </template> </draggable> </div> </template> <script> import draggable from 'vuedraggable'; export default { components: { draggable, }, data() { return { cards: [ { id: 1, title: 'Veld 1' }, { id: 2, title: 'Veld 2' } ], }; } }; </script> <style> .card { border: 1px solid #ccc; margin: 10px; padding: 10px; background-color: #f0f0f0; } .sub-card { border: 1px solid #ccc; margin: 5px; padding: 5px; background-color: #e0e0e0; } </style>
错误原因与修复方案
错误出在#item插槽的变量名上:vuedraggable的item插槽默认暴露的变量名为element,而非你写的card,所以之前的card变量实际是undefined,导致无法渲染title。
不需要额外设置属性,两种修复方式任选其一:
方式一:使用默认变量名
<template #item="{ element }"> <div class="card"> <h2>{{ element.title }}</h2> </div> </template>
方式二:重命名变量(保留card作为变量名)
<template #item="{ element: card }"> <div class="card"> <h2>{{ card.title }}</h2> </div> </template>
修正后就能正常显示每个卡片的title属性了。
内容的提问来源于stack exchange,提问作者Pigna
相关产品推荐
相关产品推荐

