如何使用值指令为元素添加自定义属性?



我有自定义属性my-custom-attribute,其中包含我需要根据布尔值添加和删除此属性的元素的id。

我已经尝试过这个代码,它工作得很好,有什么办法让它使用vejs指令吗?HTML:

<div my-custom-attribute="my_element">
...
</div>

JS:

const el = document.getElementById("some_id");
if(my_bool) {
el.setAttribute("my-custom-attribute", "#my-element");
} else {
el.removeAttribute("my-custom-attribute")
}

您可以使用下面的示例将directive注册为全局,它为您提供了三个生命周期钩子来控制行为,请阅读下面的内容并尝试实现。如果你的实现出现任何问题,请告诉我们,并启动一个单独的线程

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

Vue.directive('my-custom-directive', {
// When the bound element is inserted into the DOM...
inserted: function (el) {
// Focus the element
el.focus()
}
})

最新更新