22、自定义指令

1、什么是自定义指令

  • vue 官方提供了 v-text、v-for、v-model、v-if 等常用的指令。除此之外 vue 还允许开发者自定义指令

2、自定义指令的分类

  • vue 中的自定义指令分为两类,分别是:
    • 私有自定义指令
    • 全局自定义指令

3、 私有自定义指令

  • 在每个 vue 组件中,可以在 directives 节点下声明私有自定义指令

  • 使用私有指令时,要加上v-前缀

  • 动态绑定参数值

  • 通过binding获取指令的参数

  • update函数:

    • bind 函数只调用 1 次:当指令第一次绑定到元素时调用,当 DOM 更新时 bind 函数不会被触发。 update 函数会在每次 DOM 更新时被调用
  • 如果 insert 和update 函数中的逻辑完全相同,则对象格式的自定义指令可以简写成函数格式

<template>
  <div class="app-container">
    <h1 v-color="color">App 根组件</h1>
    <button @click="color = 'blue'">点击切换App颜色</button>
    <hr />
    <Article> </Article>
    <hr />
    <div class="box" style="display: none">
      <!-- 渲染 Left 组件和 Right 组件 -->
      <Left>
        <template v-slot:default>
          <p>这是Left组件中的p标签</p>
        </template>
      </Left>
    </div>
  </div>
</template>

<script>
import Left from "@/components/Left.vue";
import Right from "@/components/Right.vue";
import Article from "@/components/Article.vue";
export default {
  components: {
    Left,
    Right,
    Article,
  },
  data() {
    return {
      comName: "Left",
      color: "lightsalmon",
    };
  },
  // 定义私有自定义指令
  directives: {
    // color: {
    // 当指令被第一次绑定到元素上的时候,会触发bind函数
    // bind(el, binding) {
    //   // el: 表示被绑定的DOM元素对象
    //   el.style.color = binding.value;
    // },
    // 每次DOM更新时都会被调用
    //   update(el, binding) {
    //     el.style.color = binding.value;
    //   },
    // },
    
    // 如果bind和update函数处理的逻辑完全相同,则可以简写
    color(el, binding) {
      el.style.color = binding.value;
    },
  },
};
</script>

<style lang="less">
.app-container {
  padding: 1px 20px 20px;
  background-color: #efefef;
}
.box {
  display: flex;
}
</style>

4、全局自定义指令

  • 全局共享的自定义指令需要通过“Vue.directive()”进行声明
  • 在main.js中进行声明
Vue.directive('color', function (el, binding) {
  el.style.color = binding.value;
})
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值