1.全局组件

components/ItemIndex.vue
定义一个点击事件将index通过$emit传到List页面

  1. <template>
  2. <div class="item" >
  3. <div class="list" v-for="(item,index) of data" :key="item.id" @click="handleClick(index)">
  4. <slot name="icon"></slot>
  5. <img :src="item.coverImgUrl" alt="" class="bg">
  6. <p>{{item.name | format()}}</p>
  7. </div>
  8. </div>
  9. </template>
  10. <script>
  11. export default {
  12. name:"ItemIndex",
  13. props:{
  14. data:{
  15. type:Array,
  16. required:true
  17. },
  18. },
  19. //通过click事件将index传过去,父组件的事件名字要和子组件的事件名一样
  20. methods:{
  21. handleClick(index){
  22. this.$emit('click',index)
  23. }
  24. }
  25. }
  26. </script>
  27. <style scoped>
  28. .bg{
  29. width: 240px;
  30. height: 240px;
  31. }
  32. p{
  33. font-size: 32px;
  34. }
  35. .list{
  36. width: 220px;
  37. margin-bottom: 20px;
  38. position: relative;
  39. }
  40. .list:nth-child(even){
  41. border: 1px solid red;
  42. }
  43. .item{
  44. display: flex;
  45. flex-wrap: wrap;
  46. justify-content: space-between;
  47. }
  48. </style>

2.List/index.vue

定义一个点击删除事件

  1. <template>
  2. <div class="container">
  3. <item-index :data="playlists" @click="handleDelete"></item-index>
  4. </div>
  5. </template>
  6. <script>
  7. import ItemIndex from '@/components/ItemIndex.vue'
  8. export default {
  9. name:"List",
  10. data(){
  11. return{
  12. playlists:[],
  13. }
  14. },
  15. components:{
  16. ItemIndex
  17. },
  18. mounted(){
  19. this.axios.get("/top/playlist?limit=12").then(res=>{
  20. this.playlists=res.data.playlists
  21. })
  22. },
  23. methods:{
  24. handleDelete(index){
  25. this.playlists.splice(index,1)
  26. }
  27. },
  28. }
  29. </script>
  30. <style scoped>
  31. .container{
  32. display: flex;
  33. flex-wrap: wrap;
  34. justify-content: space-between;
  35. }
  36. .item:nth-child(even){
  37. border: 1px solid red;
  38. }
  39. </style>