vue的自定义指令

自定义指令

 

含义

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

自定义指令分为两类

  • 私有自定义指令

  • 全局自定义指令

注意事项

  • 自定义指令使用时需要添加 v- 前缀

  • 指令名如果是多个单词,要使用 kebab-case 短横线命名方式,不要用 camelCase 驼峰命名

  • 自定义指令三个函数里的 this 指向 window

私有自定义指令

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

使用:v-自定义指令

<div class="footer-box" v-color> //v-color,v-是固定的写法。
 <slot name="footer" :user="list"></slot>
</div>
<script>
 directives: {
   color: {
     //当指令第一次被绑定到元素上的时候,会立即触发bind函数。
     //但是数据更新的话,bind函数不会再次触发。
     //为绑定到的HTML元素设置红色文字。
     bind(el) { //bind是绑定的意思。
       //形参中的el是固定写法,为原生的DOM对象,绑定了此指令。
       el.style.color = 'red'
    }
  }
}
</script>

 

binding

<template>
 <div class="app-container">
   <h1 v-color="color">App 根组件</h1>
   <!-- 直接写颜色需要在双引号中包裹单引号,否则会寻找名叫yellow的变量。 -->
   <p v-color="'yellow'">test</p>
   <!-- 点击按钮color的数据会改变,但是如上所述,数据更新bind函数不会再次触发,因此<h1>的颜色不会再次改变。 -->
   <button @click="color='green'">change App 根组件 color</button>
 </div>
</template>

<script>
// 1. 导入需要使用的 .vue 组件

import Article from '@/components/article.vue'
export default {
 data() {
   return {
     color:'blue'
  }
},
 components: {
   Article
},
 directives: {
       color: {
           bind(el,binding) {
               console.log(binding);
               el.style.color=binding.value
          }
      }
  }
}
</script>

 

binding的console.log

//console.log(binding)
{name: 'color', rawName: 'v-color', value: 'blue', expression: 'color', modifiers: {…}, …}
def: {bind: ƒ}
expression: "color" //<p>的是 "'violet'",有单引号,这个是表达式,不能拿来用。
 modifiers: {}
name: "color" //指令的名字
 rawName: "v-color" //用的名字
 value: "blue" //binding.value 为"blue",可以直接拿来用。
[[Prototype]]: Object

 

update函数

bind函数只调用一次,当指令第一次绑定到元素时调用,当DOM调用时bind函数不会被触发,update函数会在每次DOM更新时被调用。

<script>
 components: {
   Article
},
   directives: {
     color: {
       bind(el, binding) { // 第一次生效。
         console.log(binding);
         el.style.color = binding.value
      },
         update(el, binding) { // 之后每次更新生效。
           console.log(binding);
           el.style.color = binding.value
        }
    }
  }

 

函数简写形式

如果bind和update函数内的逻辑完全相同,则对象指令的自定义格式可以简写为函数格式

<script>
 directives: {
   color(el,binding){
     el.style.color = binding.value
  }
}
</script>

 

全局自定义指令

全局共享的自定义指令需要通过vue.directive()在main.js中进行声明,示例代码如下。

Vue.directive('color',function (el,binding) {
 el.style.color=binding.value
})
 
posted @ 2023-06-16 09:15  yxxcl  阅读(43)  评论(0编辑  收藏  举报