Vue作用域插槽实战例子/使用场景

 

如何使用Vue作用域插槽?

 

随便举个简单的例子,方便理解作用域插槽的使用~

场景&需求:

现有一个新冠病毒核酸检测名单,结果呈阳性(新冠病毒感染者)的列表要加粗标红并且添加一个“标记”按钮

 

listCom.vue:

<template>
  <div>
    <h1>核酸检测结果</h1>
    <ul>
      <slot v-for="(item, index) in listData" :row=item>
        <li :key="index">
          {{item.name}} ~ {{item.positive ? '阳性' : '阴性'}}
        </li>      
      </slot>      
    </ul>
  </div>
</template>

<script>
export default {
  name: 'myListCom',
  data() {
    return {
      listData: [
        {
          name: '小明',
          positive: 0
        },
        {
          name: '小强',
          positive: 1
        },
        {
          name: '小红',
          positive: 0
        }
      ]
    }
  }
}
</script>
  
<style lang='scss' scoped>
  h1 {
    text-align: left;
    padding-left: 16px;
  }
  ul {
    display: flex;
    flex-direction: column;
    align-items: flex-start;
  }
  li {
    list-style: none;
  }
</style>
View Code
fatherCom.vue:
<template>
  <div>
    <listCom>
      <template slot-scope="scope">
        <p v-if="scope.row.positive">  // 若检测结果(positive=true)为阳性
          <strong>{{scope.row.name}} ~ {{scope.row.positive ? '阳性' : '阴性'}}</strong>
          <button>标记</button>
        </p>
      </template>
    </listCom>
  </div>
</template>

<script>
import listCom from '../../components/listCom'
export default {
  name: 'fatherCom',
  components: {
    listCom,
  }
}
</script>

<style lang='scss' scoped>
strong {
  color: red;
}
</style>
View Code

 

页面如图所示:

 

反问自己:为什么不直接在listCom.vue里面写判断?

:组件封装的意义就在复用,并且插槽的意义是可以灵活使用组件,如果又有一个页面的需求是呈阴性的列表高亮绿色 且 呈阳性的列表高亮红色但不用显示按钮呢?

这样就可以使用同一个组件只需要改变插槽的内容而不是又写一个代码重复率极高的列表组件

 

再贴一个新语法v-slot的写法:

listCom.vue 代码不变;

fatherCom.vue:

<template>
  <div>
    <listCom v-slot="scope">
      <p v-if="scope.row.positive">
        <strong>{{scope.row.name}} ~ {{scope.row.positive ? '阳性' : '阴性'}}</strong>
        <button>标记</button>
      </p>
    </listCom>
  </div>
</template>

<script>
import listCom from '../../components/listCom'
export default {
  name: 'fatherCom',
  components: {
    listCom,
  }
}
</script>

<style lang='scss' scoped>
strong {
  color: red;
}
</style>
View Code

 

页面如图所示:

 

 

 

posted @ 2021-05-31 14:49  jinfengJeff  阅读(712)  评论(0编辑  收藏  举报