Welcome to WuJiGu Developer Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
302 views
in Technique[技术] by (71.8m points)

vue组件封装,求教

通用组件:

<view v-for="(item,index) in list" :key="index">{{}}
</view>

父组件1:
list:[{name:123},{name:456}]

父组件2:
list:[{id:111},{id:222}]

两个页面中传到子组件的list中key不一样,我子组件应该如何取到父组件传过来的value值呢


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

方案1. 父组件把数据整理一下,按照要求传进去

// A.vue
<template>
    <view v-for="(item,index) in list" :key="index">
      {{item.name}}
    </view>
</template>
<script>
export default {
    props: ['list']
}
</script>
<template>
    <A :list="mappedList" />
</template>
<script>
export default {
    data: {
        list: [{id:111},{id:222}]
    },
    computed: {
        mappedList() {
            return this.list.map(i => ({name: i.id}));
        }
    }
}
</script>

方案2. 再增加一个参数告知通用组件该使用什么 key

// A.vue
<template>
    <view v-for="(item,index) in list" :key="index">
      {{item[field]}}
    </view>
</template>
<script>
export default {
    props: ['list', 'field']
}
</script>
<template>
    <A :list="list1" field="id"/>
    <A :list="list2" field="name"/>
</template>
<script>
export default {
    data: {
        list1: [{id:111},{id:222}],
        list2: [{name:111},{name:222}]
    }
}
</script>

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to WuJiGu Developer Q&A Community for programmer and developer-Open, Learning and Share
...