xgqfrms™, xgqfrms® : xgqfrms's offical website of cnblogs! xgqfrms™, xgqfrms® : xgqfrms's offical website of GitHub!

vue custom directive All In One

vue custom directives All In One

内置的指令: v-show / v-if / v-model

vue 2.x

// 注册一个全局自定义指令 `v-focus`
Vue.directive('focus', {
  // 当被绑定的元素插入到 DOM 中时……
  inserted: function (el) {
    // 聚焦元素
    el.focus()
  }
})
new Vue({
  el: '#app',
  directives: {
    focus: {
      // 局部指令
      inserted: function (el) {
        el.focus()
      }
    },
    purple: {
      // 局部指令
      inserted: function (el) {
        el.style.color = 'purple';
      },
    },
  },
  //
});
  

<h1 class="h1" v-purple>{{ message }}</h1>

<input type="text" v-focus />

https://v2.vuejs.org/v2/guide/custom-directive.html

https://cn.vuejs.org/v2/guide/custom-directive.html

钩子函数

一个指令定义对象可以提供如下几个钩子函数 (均为可选):

bind:只调用一次,指令第一次绑定到元素时调用。在这里可以进行一次性的初始化设置。

inserted:被绑定元素插入父节点时调用 (仅保证父节点存在,但不一定已被插入文档中)。

update:所在组件的 VNode 更新时调用,但是可能发生在其子 VNode 更新之前。

指令的值可能发生了改变,也可能没有。
但是你可以通过比较更新前后的值来忽略不必要的模板更新 (详细的钩子函数参数见下)。
我们会在稍后讨论渲染函数时介绍更多 VNodes 的细节。

componentUpdated:指令所在组件的 VNode 及其子 VNode 全部更新后调用。

unbind:只调用一次,指令与元素解绑时调用。

接下来我们来看一下钩子函数的参数 (即 el、binding、vnode 和 oldVnode)。

...

vue 3.x


https://v3.vuejs.org/guide/custom-directive.html

https://v3.cn.vuejs.org/guide/custom-directive.html

https://v3.cn.vuejs.org/api/application-api.html#directive

demo

refs



©xgqfrms 2012-2020

www.cnblogs.com/xgqfrms 发布文章使用:只允许注册用户才可以访问!

原创文章,版权所有©️xgqfrms, 禁止转载 🈲️,侵权必究⚠️!


posted @ 2022-03-15 00:46  xgqfrms  阅读(45)  评论(5编辑  收藏  举报