vue插槽slot的使用

vue的slot是子组件向父组件提供html自定义模版,具体做法是子组件中定义slot模版,然后在父组件中使用template去填充子组件的slot部分,子组件可以通过在slot上添加属性给父组件传递数据。

主要使用在拓展组件上,比如表格组件,让父组件可以自定义每一行的不同情况下的按钮,而子组件只需要关心一些通用的功能、布局和样式,业务逻辑部分在父组件处理,常用于一些vue的ui组件库。

具体写法可以参考例子,v-slot:slotName是vue2.6以上的写法,旧写法是slot=“slotName” slot-scope=“data”,在例子中可以看到父组件的template的位置与子组件中填充的位置没有关系,会固定按照子组件的slot位置进行渲染。

例子如下:父组件传递给子组件一个数组,然后子组件将每一个数组项传递回父组件。

<template>
  <div id="app">
    <cus-table :list="list">
      <template>默认slot</template>
      <template>默认slot2</template>

      <template v-slot:title>
        <p>具名slot</p>
      </template>

      <template v-slot:oprs="{item,index}">
        <button @click="addCount(item,index)">button</button>
      </template>
    </cus-table>
  </div>
</template>

<script>
import CusTable from "./components/CusTable.vue";

export default {
  name: "App",
  components: {
    CusTable
  },
  data: () => {
    return {
      list: [
        {
          id: 0,
          content: 0
        },
        {
          id: 1,
          content: 0
        },
        {
          id: 2,
          content: 0
        },
        {
          id: 3,
          content: 0
        }
      ]
    };
  },
  methods: {
    addCount(item, index) {
      this.list[index].content += 1;
    }
  }
};
</script>

<style>
#app {
  font-family: Avenir, Helvetica, Arial, sans-serif;
  -webkit-font-smoothing: antialiased;
  -moz-osx-font-smoothing: grayscale;
  text-align: center;
  color: #2c3e50;
  margin-top: 60px;
}
</style>

子组件CusTable:

<template>
  <div>
    <slot name="title"></slot>
    <slot></slot>
    <ol>
      <li class="list-item" v-for="(item,index) in list" :key="item.id">
        <span class="item-content">{{item.content}}</span>
        <slot name="oprs" :item="item" :index="index"></slot>
      </li>
    </ol>
  </div>
</template>

<script>
export default {
  props: {
    list: {
      type: Array
    }
  }
};
</script>

<style>
li {
  list-style: none;
}
.list-item:nth-child(odd) {
  background: #f1f1f1;
}
.item-content {
  display: inline-block;
  width: 100px;
}
</style>

效果图:
效果图

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值