vue公共列表的实现
Vue 公共列表的实现方法
在 Vue 中实现公共列表组件,可以通过封装可复用的逻辑和模板来完成。以下是几种常见的实现方式:
使用 props 和 slots
通过 props 接收列表数据,使用 slots 提供自定义渲染的灵活性。
<template>
<ul>
<li v-for="(item, index) in items" :key="index">
<slot :item="item" :index="index"></slot>
</li>
</ul>
</template>
<script>
export default {
props: {
items: {
type: Array,
required: true
}
}
}
</script>
使用时传入数据和自定义模板:
<CommonList :items="users">
<template v-slot="{ item }">
{{ item.name }} - {{ item.age }}
</template>
</CommonList>
使用 mixin 共享逻辑
创建列表逻辑的 mixin,多个组件可以复用相同的逻辑。
// listMixin.js
export default {
data() {
return {
list: [],
loading: false
}
},
methods: {
async fetchList() {
this.loading = true
try {
this.list = await api.getList()
} finally {
this.loading = false
}
}
}
}
组件中使用 mixin:
import listMixin from './listMixin'
export default {
mixins: [listMixin],
created() {
this.fetchList()
}
}
使用 renderless 组件
通过 renderless 组件封装逻辑,让父组件完全控制渲染。
<script>
export default {
props: {
items: Array,
default: () => []
},
render() {
return this.$scopedSlots.default({
items: this.items
})
}
}
</script>
使用方式:
<CommonList :items="products">
<template v-slot="{ items }">
<div v-for="item in items" :key="item.id">
{{ item.name }}
</div>
</template>
</CommonList>
使用 Vuex 管理公共状态
当多个组件需要共享列表数据时,可以使用 Vuex 集中管理状态。
// store.js
export default new Vuex.Store({
state: {
commonList: []
},
mutations: {
SET_COMMON_LIST(state, list) {
state.commonList = list
}
},
actions: {
async fetchCommonList({ commit }) {
const list = await api.getList()
commit('SET_COMMON_LIST', list)
}
}
})
组件中访问和更新:
computed: {
commonList() {
return this.$store.state.commonList
}
},
methods: {
refreshList() {
this.$store.dispatch('fetchCommonList')
}
}
最佳实践建议
- 对于简单列表,props + slots 组合足够灵活
- 当多个组件需要相同逻辑时,考虑使用 mixin 或 renderless 组件
- 对于全局共享的数据,使用 Vuex 管理更合适
- 始终为列表项提供唯一的 key 属性
- 考虑添加加载状态和错误处理机制
以上方法可以根据实际需求组合使用,构建出灵活高效的公共列表组件。







