Vue自定义指令的update钩子为什么没触发样式更新?

宇文馨翼 阅读 29

我在用Vue写一个高亮文字的自定义指令,想让元素背景色在hover时动态变化。按文档写了bind和update钩子,但发现update根本没执行,hover的时候样式没反应。

代码是这样的:


<template>
  <div v-highlight="{color: activeColor}">测试文字</div>
</template>

<script>
export default {
  directives: {
    highlight(el, binding) {
      el.style.backgroundColor = binding.value.color
      // 这里写了update钩子但没生效
      const update = () => {
        el.style.color = 'red'
      }
    }
  },
  data() {
    return { activeColor: 'yellow' }
  }
}
</script>

我试过把update写成函数形式,但控制台没报错就是不触发。是不是钩子写法有问题?或者动态数据没绑定上?

我来解答 赞 6 收藏
二维码
手机扫码查看
1 条解答
Des.东景
你这update钩子根本没挂到指令对象上啊,写错地方了。Vue自定义指令的钩子函数要直接作为指令对象的属性,不能在内部定义。改成这样:

directives: {
highlight: {
bind(el, binding) {
el.style.backgroundColor = binding.value.color
},
update(el, binding) {
el.style.color = 'red'
}
}
}
点赞 5
2026-02-06 00:03