vue2-自定义指令

1,321 阅读2分钟

Vue2-自定义指令

1. 什么是指令?

  • 指令就是特殊的属性,用来操作 dom 元素的。
  • vue 也给我们定义了一些指令,例如 v-show v-if 等。

2. 指令的生命周期函数

export default {
    // 这个函数只会被调用一次,就是绑定元素的时候,可以在这里做初始化工作
    bind(el,binding,vnode,oldVode){
        // el 绑定的 dom 元素
        // bingding 一些参数,很有用的,建议去读一下官方文档,传递的一些参数也在里面
        // vnode 虚拟 dom
        // oldVode 上一个虚拟节点,仅在 update 和 componentUpdated 钩子中可用
    },
    // 被绑定的元素 插入父元素的时候调用该函数--仅保证父节点存在
    inserted(el,binding,vnode,oldVode){
        
    },
    // 所在组件的 vnode 更新时调用
    update(el,binding,vnode,oldVode){
        
    },
    // 指令所在的组件的 vnode 及其 子组件的 vnode 全部更新之后调用
    componentUpdated(el,binding,vnode,oldVode){
        
    },
    // 指令与元素解绑时调用,只调用一次
    unBind(el,binding,vnode,oldVode){
        
    }
}

3. 自定义指令-局部

1. 第一种:直接在 directives 中书写自定义指令

<template>
  <div>
    用户名: <input type="text" v-default-value="val">
  </div>
</template>

<script>
export default {
  data() {
    return {
      val: 'username'
    }
  },
    
// 自定义指令
  directives: {
    defaultValue: function (el, binding) {
      console.log(binding);
      el.value = binding.value   //  binding.value 的值  保存的是指令的 等号 后面的属性值
    }
  }
};
    
</script>

2. 第二种:指令书写在单独的js文件中

指令书写在 src 新建一个 directives 文件夹,在里面新建一个 focus.js 文件。

export default {
    // 被绑定元素插入父节点的调用
    inserted(el) {
        el.focus()
    },
}

组件:在组件中引入书写指令的 js 模块,并且在 directives 选项中注册即可使用。

<template>
  <div>
    用户名: <input v-focus type="text">
  </div>
</template>

<script>
// 
import focus from "@/utils/directives/focus";

export default {
  directives: {
    focus,
  }
};
</script>

3. 第三种:动态指令参数

写法:v-mydirective:[argument]="value"

就是可以给指令传递一些参数,argument 是指令的参数,value 是指令的属性值,argument 可以在 binding 参数的 arg 中拿到,value 可以在 binding.value 中拿到,value 可以是基础数据类型,也可以是复杂数据类型,数组,对象等。

export default {
    bind(el, binding) {
        console.log(binding);
        el.style[binding.arg] = binding.value + "px"
    }
}
<template>
  <div v-fixed:[direction]="300" class="box"></div>
</template>

<script>
import fixed from "@/utils/directives/fixed";
export default {
  data() {
    return {
      direction: 'right',
    }
  },

  directives: {
    fixed,
  }
};
</script>

<style lang="scss" scoped>
.box {
  height: 200px;
  width: 200px;
  background-color: skyblue;
  position: fixed;
}
</style>

4. 全局指令

直接在 man.js 中定义指令

import Vue from 'vue'
import App from './App.vue'
import router from './router'
import store from './store'

// 这里定义的是全局指令
Vue.directive("font-color", {
  bind(el, binding) {
    el.style.color = binding.value
  }
})

new Vue({
  router,
  store,
  render: h => h(App)
}).$mount('#app')

使用:全局指令无需注册,直接在组件中使用即可。

<template>
  <div v-font-color="colorVal">
    文字文字
  </div>
</template>

<script>
export default {
  data() {
    return {
      colorVal: '#00ff00'
    };
  }
};
</script>