gpt4 book ai didi

javascript - 使用 Vuejs,如何以正确的方式在 v-for 循环中使用模态组件

转载 作者:搜寻专家 更新时间:2023-10-30 22:18:57 25 4
gpt4 key购买 nike

在我的 vue.js 应用中,我需要显示用户可以点击的项目列表。

单击时,这些项目中的每一个都应触发模态,其中包含有关用户刚刚单击的项目的其他信息。

到目前为止,我的 Items.vue 组件中有:

<template>
<div id="content">
<li v-for="item in items" class="list-item pa2 ba">
<div class="f5 pt2 pb2">
<span>{{item.name}}</span>
</div>
</li>
</div>
</template>

<script>
import Items from '@/api/items';

export default {
name: 'items',
asyncComputed: {
items: {
async get() {
const items = await Items.getAll();
return items.data;
},
default: []
}
},
components: {}
}
</script>

现在,我可以简单地在 v-for 循环中添加一个模态组件,从而为每个项目创建一个模态,但这似乎并不理想,例如,我有一个列表数以千计的项目。

这让我相信模态框应该放在应用程序的根目录下(在我的例子中是 App.vue),如下所示:

<template>
<div id="app">
<modal></modal>
<router-view></router-view>
</div>
</template>

<script>
export default {
name: 'app'
}
</script>

然后在我需要的时候以某种方式触发自定义数据。

但是,我不确定如何进行。如何使用 v-for 循环内的自定义信息触发此模态,该循环位于 App.vue 的子组件中?

最佳答案

这两个链接帮助我解决了这个问题:

#在你的父组件中您不必为 v-for 循环中的每个项目创建模态,只需在父级的开头包含模态组件,然后使用 v-if="..."和 props。

<template>
<div>
<modal v-if="modalVisible" @close="modalVisible = false" :data="modalData"/>

<div v-for="item in items">
<button type="button" @click="openModal(item)">Open Modal</button>
</div>

</div>
</template>

然后在你的脚本中:

import modal from './Modal'

export default {
components: {
modal
},
data() {
return {
modalVisible: false,
modalData: null
}
},
methods: {
openModal(data) {
this.modalData = data
this.modalVisible = true
},
}

#在你的子(模态)组件中在您的模式中,您现在可以执行以下操作:

模板:

<template>
{{ data.foo }}
<button @click="$emit('close')">Cancel</button>
</template>

脚本

<script>
export default {
props: ['user']
};
</script>

希望对您有所帮助:-)

关于javascript - 使用 Vuejs,如何以正确的方式在 v-for 循环中使用模态组件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46618266/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com