13-Vue基础之自定义指令与插槽的使用

个人名片:
😊作者简介:一名大二在校生
🤡 个人主页:坠入暮云间x
🐼
座右铭:懒惰受到的惩罚不仅仅是自己的失败,还有别人的成功。
🎅**学习目标: 坚持每一次的学习打卡

一、学习目标

1.自定义指令

  • 基本语法(全局、局部注册)
  • 指令的值
  • v-loading的指令封装

2.插槽

  • 默认插槽
  • 具名插槽
  • 作用域插槽

二、自定义指令

1.指令介绍

  • 内置指令:v-html、v-if、v-bind、v-on… 这都是Vue给咱们内置的一些指令,可以直接使用

  • 自定义指令:同时Vue也支持让开发者,自己注册一些指令。这些指令被称为自定义指令

    每个指令都有自己各自独立的功能

2.自定义指令

概念:自己定义的指令,可以封装一些DOM操作,扩展额外的功能

3.自定义指令语法

  • 全局注册

    //在main.js中
    Vue.directive('指令名', {
      "inserted" (el) {
        // 可以对 el 标签,扩展额外功能
        el.focus()
      }
    })
    
  • 局部注册

    //在Vue组件的配置项中
    directives: {
      "指令名": {
        inserted () {
          // 可以对 el 标签,扩展额外功能
          el.focus()
        }
      }
    }
    
  • 使用指令

    注意:在使用指令的时候,一定要先注册再使用,否则会报错
    使用指令语法: v-指令名。如:

    注册指令时不用v-前缀,但使用时一定要加v-前缀

4.指令中的配置项介绍

inserted:被绑定元素插入父节点时调用的钩子函数

el:使用指令的那个DOM元素

5.代码示例

需求:当页面加载时,让元素获取焦点(autofocus在safari浏览器有兼容性

App.vue

  <div>
    <h1>自定义指令</h1>
    <input v-focus ref="inp" type="text">
  </div>

三、自定义指令-指令的值

1.需求

实现一个 color 指令 - 传入不同的颜色, 给标签设置文字颜色

2.语法

1.在绑定指令时,可以通过“等号”的形式为指令 绑定 具体的参数值

<div v-color="color">我是内容</div>

2.通过 binding.value 可以拿到指令值,指令值修改会 触发 update 函数

directives: {
  color: {
    inserted (el, binding) {
      el.style.color = binding.value
    },
    update (el, binding) {
      el.style.color = binding.value
    }
  }
}

3.代码示例

App.vue

<template>
  <div>
     <!--显示红色--> 
    <h2 v-color="color1">指令的值1测试</h2>
     <!--显示蓝色--> 
    <h2 v-color="color2">指令的值2测试</h2>
     <button>
        改变第一个h1的颜色
    </button>
  </div>
</template>

<script>
export default {
  data () {
    return {
      color1: 'red',
      color2: 'blue'
    }
  }
}
</script>

<style>

</style>

四、自定义指令-v-loading指令的封装

1.场景

实际开发过程中,发送请求需要时间,在请求的数据未回来时,页面会处于空白状态 => 用户体验不好

2.需求

封装一个 v-loading 指令,实现加载中的效果

3.分析

1.本质 loading效果就是一个蒙层,盖在了盒子上

2.数据请求中,开启loading状态,添加蒙层

3.数据请求完毕,关闭loading状态,移除蒙层

4.实现

1.准备一个 loading类,通过伪元素定位,设置宽高,实现蒙层

2.开启关闭 loading状态(添加移除蒙层),本质只需要添加移除类即可

3.结合自定义指令的语法进行封装复用

.loading:before {
  content: "";
  position: absolute;
  left: 0;
  top: 0;
  width: 100%;
  height: 100%;
  background: #fff url("./loading.gif") no-repeat center;
}

5.准备代码

<template>
  <div class="main">
    <div class="box">
      <ul>
        <li v-for="item in list" :key="item.id" class="news">
          <div class="left">
            <div class="title">{{ item.title }}</div>
            <div class="info">
              <span>{{ item.source }}</span>
              <span>{{ item.time }}</span>
            </div>
          </div>
          <div class="right">
            <img :src="item.img" alt="">
          </div>
        </li>
      </ul>
    </div> 
  </div>
</template>

<script>
// 安装axios =>  yarn add axios || npm i axios
import axios from 'axios'

// 接口地址:http://hmajax.itheima.net/api/news
// 请求方式:get
export default {
  data () {
    return {
      list: [],
      isLoading: false,
      isLoading2: false
    }
  },
  async created () {
    // 1. 发送请求获取数据
    const res = await axios.get('http://hmajax.itheima.net/api/news')
    
    setTimeout(() => {
      // 2. 更新到 list 中,用于页面渲染 v-for
      this.list = res.data.data
    }, 2000)
  }
}
</script>

<style>
.loading:before {
  content: '';
  position: absolute;
  left: 0;
  top: 0;
  width: 100%;
  height: 100%;
  background: #fff url('./loading.gif') no-repeat center;
}

.box2 {
  width: 400px;
  height: 400px;
  border: 2px solid #000;
  position: relative;
}



.box {
  width: 800px;
  min-height: 500px;
  border: 3px solid orange;
  border-radius: 5px;
  position: relative;
}
.news {
  display: flex;
  height: 120px;
  width: 600px;
  margin: 0 auto;
  padding: 20px 0;
  cursor: pointer;
}
.news .left {
  flex: 1;
  display: flex;
  flex-direction: column;
  justify-content: space-between;
  padding-right: 10px;
}
.news .left .title {
  font-size: 20px;
}
.news .left .info {
  color: #999999;
}
.news .left .info span {
  margin-right: 20px;
}
.news .right {
  width: 160px;
  height: 120px;
}
.news .right img {
  width: 100%;
  height: 100%;
  object-fit: cover;
}
</style>

五、插槽-默认插槽

1.作用

让组件内部的一些 结构 支持 自定义

在这里插入图片描述

2.需求

将需要多次显示的对话框,封装成一个组件

3.问题

组件的内容部分,不希望写死,希望能使用的时候自定义。怎么办

4.插槽的基本语法

  1. 组件内需要定制的结构部分,改用****占位
  2. 使用组件时, ****标签内部, 传入结构替换slot
  3. 给插槽传入内容时,可以传入纯文本、html标签、组件

在这里插入图片描述

5.代码示例

MyDialog.vue

<template>
  <div class="dialog">
    <div class="dialog-header">
      <h3>友情提示</h3>
      <span class="close">✖️</span>
    </div>

    <div class="dialog-content">
      您确定要进行删除操作吗?
    </div>
    <div class="dialog-footer">
      <button>取消</button>
      <button>确认</button>
    </div>
  </div>
</template>

<script>
export default {
  data () {
    return {

    }
  }
}
</script>

<style scoped>
* {
  margin: 0;
  padding: 0;
}
.dialog {
  width: 470px;
  height: 230px;
  padding: 0 25px;
  background-color: #ffffff;
  margin: 40px auto;
  border-radius: 5px;
}
.dialog-header {
  height: 70px;
  line-height: 70px;
  font-size: 20px;
  border-bottom: 1px solid #ccc;
  position: relative;
}
.dialog-header .close {
  position: absolute;
  right: 0px;
  top: 0px;
  cursor: pointer;
}
.dialog-content {
  height: 80px;
  font-size: 18px;
  padding: 15px 0;
}
.dialog-footer {
  display: flex;
  justify-content: flex-end;
}
.dialog-footer button {
  width: 65px;
  height: 35px;
  background-color: #ffffff;
  border: 1px solid #e1e3e9;
  cursor: pointer;
  outline: none;
  margin-left: 10px;
  border-radius: 3px;
}
.dialog-footer button:last-child {
  background-color: #007acc;
  color: #fff;
}
</style>

App.vue

<template>
  <div>
    <MyDialog>
    </MyDialog>
  </div>
</template>

<script>
import MyDialog from './components/MyDialog.vue'
export default {
  data () {
    return {

    }
  },
  components: {
    MyDialog
  }
}
</script>

<style>
body {
  background-color: #b3b3b3;
}
</style>

6.总结

场景:组件内某一部分结构不确定,想要自定义怎么办

使用:插槽的步骤分为哪几步?

六、插槽-后备内容(默认值)

1.问题

通过插槽完成了内容的定制,传什么显示什么, 但是如果不传,则是空白

在这里插入图片描述

能否给插槽设置 默认显示内容 呢?

2.插槽的后备内容

封装组件时,可以为预留的 <slot> 插槽提供后备内容(默认内容)。

3.语法

在 标签内,放置内容, 作为默认显示内容

4.效果

  • 外部使用组件时,不传东西,则slot会显示后备内容

    在这里插入图片描述
    在这里插入图片描述

  • 外部使用组件时,传东西了,则slot整体会被换掉

    在这里插入图片描述

5.代码示例

App.vue

<template>
  <div>
    <MyDialog></MyDialog>
    <MyDialog>
      你确认要退出么
    </MyDialog>
  </div>
</template>

<script>
import MyDialog from './components/MyDialog.vue'
export default {
  data () {
    return {

    }
  },
  components: {
    MyDialog
  }
}
</script>

<style>
body {
  background-color: #b3b3b3;
}
</style>

七、插槽-具名插槽

1.需求

一个组件内有多处结构,需要外部传入标签,进行定制

上面的弹框中有三处不同,但是默认插槽只能定制一个位置,这时候怎么办呢?

2.具名插槽语法

  • 多个slot使用name属性区分名字

    在这里插入图片描述

  • template配合v-slot:名字来分发对应标签

    在这里插入图片描述

3.v-slot的简写

v-slot写起来太长,vue给我们提供一个简单写法 v-slot —> #

4.总结

  • 组件内 有多处不确定的结构 怎么办?
  • 具名插槽的语法是什么?
  • v-slot:插槽名可以简化成什么?

八、作用域插槽

1.插槽分类

  • 默认插槽

  • 具名插槽

    插槽只有两种,作用域插槽不属于插槽的一种分类

2.作用

定义slot 插槽的同时, 是可以传值的。给 插槽 上可以 绑定数据,将来 使用组件时可以用

3.场景

封装表格组件
在这里插入图片描述

4.使用步骤

  1. 给 slot 标签, 以 添加属性的方式传值

    <slot :id="item.id" msg="测试文本"></slot>
    
  2. 所有添加的属性, 都会被收集到一个对象中

    { id: 3, msg: '测试文本' }
    
  3. 在template中, 通过 #插槽名= "obj" 接收,默认插槽名为 default

    <MyTable :list="list">
      <template #default="obj">
        <button @click="del(obj.id)">删除</button>
      </template>
    </MyTable>
    

5.代码示例

MyTable.vue

<template>
  <table class="my-table">
    <thead>
      <tr>
        <th>序号</th>
        <th>姓名</th>
        <th>年纪</th>
        <th>操作</th>
      </tr>
    </thead>
    <tbody>
      <tr>
        <td>1</td>
        <td>赵小云</td>
        <td>19</td>
        <td>
          <button>
          	查看    
    	  </button>
        </td>
      </tr>
        <tr>
        <td>1</td>
        <td>张小花</td>
        <td>19</td>
        <td>
          <button>
          	查看    
    	  </button>
        </td>
      </tr>
        <tr>
        <td>1</td>
        <td>孙大明</td>
        <td>19</td>
        <td>
          <button>
          	查看    
    	  </button>
        </td>
      </tr>
    </tbody>
  </table>
</template>

<script>
export default {
  props: {
    data: Array
  }
}
</script>

<style scoped>
.my-table {
  width: 450px;
  text-align: center;
  border: 1px solid #ccc;
  font-size: 24px;
  margin: 30px auto;
}
.my-table thead {
  background-color: #1f74ff;
  color: #fff;
}
.my-table thead th {
  font-weight: normal;
}
.my-table thead tr {
  line-height: 40px;
}
.my-table th,
.my-table td {
  border-bottom: 1px solid #ccc;
  border-right: 1px solid #ccc;
}
.my-table td:last-child {
  border-right: none;
}
.my-table tr:last-child td {
  border-bottom: none;
}
.my-table button {
  width: 65px;
  height: 35px;
  font-size: 18px;
  border: 1px solid #ccc;
  outline: none;
  border-radius: 3px;
  cursor: pointer;
  background-color: #ffffff;
  margin-left: 5px;
}
</style>

App.vue

<template>
  <div>
    <MyTable :data="list"></MyTable>
    <MyTable :data="list2"></MyTable>
  </div>
</template>

<script>
  import MyTable from './components/MyTable.vue'
  export default {
    data () {
      return {
     	list: [
            { id: 1, name: '张小花', age: 18 },
            { id: 2, name: '孙大明', age: 19 },
            { id: 3, name: '刘德忠', age: 17 },
          ],
          list2: [
            { id: 1, name: '赵小云', age: 18 },
            { id: 2, name: '刘蓓蓓', age: 19 },
            { id: 3, name: '姜肖泰', age: 17 },
          ]
      }
    },
    components: {
      MyTable
    }
  }
</script>

6.总结

1.作用域插槽的作用是什么?

作用域插槽的主要作用如下:

  1. 封装组件逻辑:通过使用作用域插槽,可以将组件的逻辑封装在子组件中,避免在父组件中过度使用 props 和事件。这有助于保持组件的纯度和可重用性。

  2. 分离关注点:作用域插槽允许你在父组件和子组件中分别处理不同的逻辑,使组件之间的职责更加明确。这样可以降低组件之间的耦合度,提高代码的可维护性。

  3. 提高代码可读性:作用域插槽可以让父组件和子组件的代码更加简洁,同时保持清晰的逻辑。这样可以提高代码的可读性,便于团队成员理解和维护。

自定义指令有两种类型:全局指令和局部指令。

  1. 全局指令:全局指令是注册在 Vue 构造函数上的指令,可以在整个应用程序的任何实例中使用。我们可以使用 Vue.directive() 方法来创建全局指令,该方法接受两个参数:指令名称和指令对象。指令对象包含指令的行为和样式。
2.自定义指令的作用是什么?
1.代码复用:通过自定义指令,我们可以创建一些通用的功能,并将它们封装成指令。这样在开发其他组件时,可以方便地复用这些功能,减少重复代码。
2.组件解耦:自定义指令使得组件之间的通信更加灵活。通过使用局部指令,我们可以在不修改组件源代码的情况下,为组件添加额外的行为和样式。这有助于提高组件的独立性和可维护性。
  1. 提高开发效率:自定义指令可以帮助我们快速地实现一些特定的功能,而不需要逐个修改组件的源代码。这可以大大提高开发效率,降低开发成本。
    4.提高用户体验:通过自定义指令,我们可以为用户提供更加丰富的交互体验。例如,我们可以创建一个自定义指令来实现自动聚焦功能,这样用户在打开页面时,焦点会自动定位到某个输入框,提高用户体验。
  • 3
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值