vue--自定义钩子函数

钩子函数:

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

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

  • update:所在组件的 VNode 更新时调用,但是可能发生在其子 VNode 更新之前。指令的值可能发生了改变,也可能没有。但是你可以通过比较更新前后的值来忽略不必要的模板更新 (详细的钩子函数参数见下)。

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

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

钩子函数参数:

  • el:指令所绑定的元素,可以用来直接操作 DOM。
  • binding:一个对象,包含以下 property:
    • name:指令名,不包括 v- 前缀。
    • value:指令的绑定值,例如:v-my-directive="1 + 1" 中,绑定值为 2
    • oldValue:指令绑定的前一个值,仅在 updatecomponentUpdated 钩子中可用。无论值是否改变都可用。
    • 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 编译生成的虚拟节点。
  • oldVnode:上一个虚拟节点,仅在 updatecomponentUpdated 钩子中可用。

除了 el 之外,其它参数都应该是只读的,切勿进行修改。如果需要在钩子之间共享数据,建议通过元素的 dataset 来进行。

示例:

App.vue

<template>
  <div id="app">
    <MyDirective />
  </div>
</template>

<script>
import MyDirective from "./components/MyDirective.vue"

export default {
  name: 'App',
  components: {
    MyDirective
  },
}
</script>

<style>
#app {
  font-family: Avenir, Helvetica, Arial, sans-serif;
  -webkit-font-smoothing: antialiased;
  -moz-osx-font-smoothing: grayscale;
  text-align: center;
  color: #2c3e50;
  margin-top: 60px;
}
</style>

MyDirective.vue

<template>
  <div>
      <!-- <input type="text" v-focus> -->
      <button @click="message='改变内容'">改变内容</button>
      <p v-myShow="true">{{ message }}</p>
  </div>
</template>

<script>
export default {
    data () {
        return {
            message:"查看钩子函数"
        }
    }
}
</script>

<style>

</style>

index.js

import Vue from "vue"

Vue.directive('myShow', {
    bind(el, binding, vnode, oldVnode) {
        console.log("初始化设置时调用");
    },
    inserted(el, binding, vnode, oldVnode) {
        console.log(binding.name);
        console.log(binding.value);
        console.log("插入节点时调用");
    },
    update(el, binding, vnode, oldVnode) {
        console.log("改变之前" + el.innerHTML);
        console.log("内容发生改变时调用");
    },
    componentUpdated(el, binding, vnode, oldVnode) {
        console.log("改变之后" + el.innerHTML);
        console.log("父子节点发生改变时调用");
    },
    unbind(el, binding, vnode, oldVnode) {
        console.log("解绑时调用");
    }
})

 点击“查看内容”按钮后,

 

 

 

  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

小白小白从不日白

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值