通过实例学习Vue 2.6新增的v-slot

2019-09-14  本文已影响0人  microkof

文档

https://cn.vuejs.org/v2/guide/components-slots.html

虽然Vue的文档大多数言之不详,但是这次插槽真的是把事情都说清楚了,我就不多说了。

今天练习一个空状态组件的编写方法,为了简化代码,使用了vue-element-admin作为环境。

空状态组件

Empty组件编写

<template>
  <div class="empty-container" :style="{ 'height': height }">
    <svg-icon :icon-class="iconName" class="empty-icon" />
    <p class="el-link el-link--default"><slot name="description">什么也没有</slot></p>
    <el-button v-if="clickButton" :type="buttonType" @click="clickButton"><slot name="button">确定</slot></el-button>
  </div>
</template>

<script>
export default {
  name: 'Empty',
  props: {
    height: {
      type: String,
      default: '100%'
    },
    iconName: {
      type: String,
      default: 'empty'
    },
    buttonType: {
      type: String,
      default: 'primary'
    },
    clickButton: {
      type: Function,
      default: undefined
    }
  }
}
</script>

<style lang="scss" scoped>
.empty-container {
  display: flex;
  justify-content: center;
  align-items: center;
  flex-direction: column;
  min-height: 200px;
  .empty-icon {
    font-size: 100px;
  }
}
</style>

父组件编写

template如下,其中#description#button就是具名插槽,当然这是缩写形式,全写形式是v-slot:descriptionv-slot:button

    <empty height="320px" :icon-name="iconName" :click-button="clickButton">
      <template #description>
        一行说明文字
      </template>
      <template #button>
        按钮文字
      </template>
    </empty>

script如下,传入一些data和一个method。

  data() {
    return {
      iconName: 'empty',
      aaa: '1'
    }
  },
  methods: {
    clickButton() {
      alert(this.aaa)
    }
  }
上一篇 下一篇

猜你喜欢

热点阅读