VUE的组件传参(数组)+动态样式添加

app.vue

<template>
  <div>
    <!-- 组件传参:数组类型 -->
    <!-- <my-list items="skills" /> -->
    <my-list :items="skills" />
    <!-- 组件的最大用途: 复用性 - 界面相同但是数据不同 -->
    <my-list :items="['亮亮', '亚楠', '小新', '铭铭', '思远']" />
    <!-- 结合for循环使用 -->
    <!-- item是data中的元素, 数组类型 -->
    <my-list v-for="item in data" :items="item" />
  </div>
</template>

<script>
import MyList from './components/MyList.vue'
export default {
  components: { MyList },
  data() {
    return {
      skills: ['html', 'css', 'js', 'express', 'vue'],
      data: [
        ['SQL', 'MySQL', 'Express', 'Node.js'],
        ['CSS', 'SASS', 'boot', 'ajax', 'html'],
        ['js高级', 'dom', 'jQuery', 'vue'],
        ['elementUI', 'vantUI', '微信小程序', 'HTML5高级'],
      ],
    }
  },
}
</script>

<style lang="scss" scoped></style>

组件my-list

<template>
  <div class="list">
    <div>排行榜:</div>
    <!-- <div>{{ items }}</div> -->
    <div v-for="(item, index) in items" class="cell">
      <!-- 动态样式 :class="{类名: true/false}" -->
      <!-- hl样式类, 在 index序号 <= 2 时生效 -->
      <span :class="{ hl: index <= 2 }">{{ index + 1 }}</span>
      <span>{{ item }}</span>
    </div>
  </div>
</template>

<script>
export default {
  // 自定义属性
  props: ['items'],
}
</script>

<style lang="scss" scoped>
.list {
  display: inline-block;
  margin: 0 10px 10px 0;
  width: 200px;
  vertical-align: top;
}

.cell {
  background-color: lightblue;
  margin: 4px;
  padding: 5px;
  border-radius: 3px;
  box-shadow: 0 0 2px 1px rgba(0, 0, 0, 0.2);
  transition: 0.2s;
  &:hover {
    padding-left: 20px;
  }
  > span:first-child {
    display: inline-block;
    width: 20px;
    height: 20px;
    background-color: white;
    text-align: center;
    margin-right: 4px;
    border-radius: 2px;
    // 同时带有 class='hl' 的
    &.hl {
      background-color: orange;
    }
  }
}
</style>


版权声明:本文为m0_66051368原创文章,遵循CC 4.0 BY-SA版权协议,转载请附上原文出处链接和本声明。