Vue自定义指令详解

 

1、背景

最近在面试找工作,然后面试官就问了有关自定义指令的问题,然后由于平时自定义指令用的不多,只是看过官方文档大概知道需要用到Vue.directive来自定义指令;面试结束之后,立刻就去网上找有关自定义指令的资料,发现自定义指令还是有很多学问的,于是就想写个博客记录下也是鞭策自己,要多尝试,多学习!!!

这是官方文档有关自定义指令的模块;自定义指令包括全局自定义指令以及局部自定义指令

 

2、局部自定义指令

果想注册局部指令,组件中也接受一个 directives 的选项:

@Component({
name: "CustomDirectives",
components: {},
directives: {
  //   局部自定义指令
  custom1: {
    inserted(el) {
      console.log("el", el);
      el.style.position = "absolute";
      el.style.top = " 50%";
      el.style.left = "50%";
      el.style.transform = "translate(-50%,-50%)";
      el.innerText = "加载中...";
      el.style.padding = "10px";
      el.style.color = "#333";
    },
  },
},
})

 

3、全局自定义指令

Vue.directive("custom2", {
inserted(el, binding) {
  console.log("binding", binding);
  if (binding && binding.value) {
    el.innerText = "测试全局自定义指令";
    console.log("el", el);
    el.style.position = "absolute";
    el.style.top = " 50%";
    el.style.left = "50%";
    el.style.transform = "translate(-50%,-50%)";
    el.style.padding = "10px";
    el.style.color = "#333";
  }
},
});

4.1 自定义指令钩子函数

  • bind:只调用一次,指令第一次绑定到元素时调用。在这里可以进行一次性的初始化设置。
  • inserted:被绑定元素插入父节点时调用 (仅保证父节点存在,但不一定已被插入文档中)。
  • update:所在组件的 VNode 更新时调用,但是可能发生在其子 VNode 更新之前。指令的值可能发生了改变,也可能没有。但是你可以通过比较更新前后的值来忽略不必要的模板更新 (详细的钩子函数参数见下)。
  • componentUpdated:指令所在组件的 VNode 及其子 VNode 全部更新后调用。
  • unbind:只调用一次,指令与元素解绑时调用。

4.2 钩子函数参数

  • el:指令所绑定的元素,可以用来直接操作 DOM。
  • binding:一个对象,

包含以下 property:

  • name:指令名,不包括 v- 前缀。
  • value:指令的绑定值,例如:v-my-directive="1 + 1" 中,绑定值为 2。
  • oldValue:指令绑定的前一个值,仅在 update 和 componentUpdated 钩子中可用。无论值是否改变都可用。
  • expression:字符串形式的指令表达式。例如 v-my-directive="1 + 1" 中,表达式为 "1 + 1"。
  • arg:传给指令的参数,可选。例如 v-my-directive:foo 中,参数为 "foo"。
  • modifiers:一个包含修饰符的对象。例如:v-my-directive.foo.bar 中,修饰符对象为 { foo: true, bar: true }。
  • vnode:Vue 编译生成的虚拟节点。移步 VNode API 来了解更多详情。
  • oldVnode:上一个虚拟节点,仅在 update 和 componentUpdated 钩子中可用。

4.3 动态指令传参

Vue.directive("custom2", {
inserted(el, binding) {
  console.log("binding", binding);
  if (binding && binding.value) {
    el.innerText = "测试全局自定义指令";
    console.log("el", el);
    el.style.position = "absolute";
    el.style.top = " 50%";
    const arg = (binding as any).arg;
    el.style[arg] = "50%";
    el.style.transform = "translate(-50%,-50%)";
    el.style.padding = "10px";
    el.style.color = "#333";
  }
},
});


<div v-custom2:[direction]="true"></div>

private direction= 'left';

 

5、拓展

问完自定义指令之后,面试官又问了你平时都用到哪些默认的指令?
我回答:v-for v-if v-show v-model等等
然后问题就来了---v-for和v-if能同时使用吗
我答:不能,同时使用会有性能问题。
问:为什么会有性能问题?
我答:如果每一次都需要遍历整个数组,将会影响速度,尤其是当之需要渲染很小一部分的时候。
问:那如何避免v-for和v-if一起使用呢?
我:??? 工作中这种情况遇到的不多,一般都是把v-if放到遍历的循环里面,(其实还是有性能问题)
面试结束之后,去查了下资料,网上说v-for和v-if不应该一起使用,必要情况下应该替换成computed属性。

关于Vue自定义指令详细的文章就介绍至此,更多相关Vue自定义指令内容请搜索编程宝库以前的文章,希望以后支持编程宝库

页面:base:<template><div class="tab-container"> <h1 style="text-align: center"> ...