自定义指令directives
directives
-
类型:
Object
-
详细:
声明一组可用于组件实例中的指令。
-
用法:
const app = createApp({}) app.component('focused-input', { directives: { focus: { mounted(el) { el.focus() } } }, template: `<input v-focus>` })
简介
除了核心功能默认内置的指令 (例如 v-model
和 v-show
),Vue 也允许注册自定义指令。
注意,在 Vue 中,代码复用和抽象的主要形式是组件。然而,有的情况下,你仍然需要对普通 DOM 元素进行底层操作,这时候就会用到自定义指令。
例:
当页面加载时,输入框将获得焦点 (注意:autofocus
在移动版 Safari 上不工作)。
事实上,如果你在打开这个页面后还没有点击过任何内容,那么此时这个输入框就应当处于聚焦状态。
const app = Vue.createApp({}) // 注册一个全局自定义指令 `v-focus` app.directive('focus', { // 当被绑定的元素挂载到 DOM 中时…… mounted(el) { // 聚焦元素 el.focus() } })
如果想注册局部指令,组件中也接受一个 directives
的选项:
directives: { focus: { // 指令的定义 mounted(el) { el.focus() } } } //然后你可以在模板中任何元素上使用新的 v-focus attribute,如下: <input v-focus />
钩子函数
一个指令定义对象可以提供如下几个钩子函数 (均为可选):
-
created
:在绑定元素的 attribute 或事件监听器被应用之前调用。在指令需要附加在普通的v-on
事件监听器调用前的事件监听器中时,这很有用。 -
beforeMount
:当指令第一次绑定到元素并且在挂载父组件之前调用。 -
mounted
:在绑定元素的父组件被挂载前调用。 -
beforeUpdate
:在更新包含组件的 VNode 之前调用。
-
updated
:在包含组件的 VNode 及其子组件的 VNode 更新后调用。 -
beforeUnmount
:在卸载绑定元素的父组件之前调用 -
unmounted
:当指令与元素解除绑定且父组件已卸载时,只调用一次。
还可以加动态的一个参数,比如一开始我要某个元素 高 = 500,那么就在el 后面加个参数叫binding,然后取值是 binding.value ,例:
指令的参数可以是动态的。例如,在 v-mydirective:[argument]="value"
中,argument
参数可以根据组件实例数据进行更新!这使得自定义指令可以在应用中被灵活使用。
例如你想要创建一个自定义指令,用来通过固定布局将元素固定在页面上。我们可以创建一个自定义指令,它的值以像素为单位更新被固定元素的垂直位置,如下所示:
<div id="dynamic-arguments-example" class="demo"> <p v-pin="200">Stick me 200px from the top of the page</p> </div>
const app = Vue.createApp({}) app.directive('pin', { mounted(el, binding) { el.style.position = 'fixed' // binding.value 是我们传递给指令的值——在这里是 200 el.style.top = binding.value + 'px' } }) app.mount('#dynamic-arguments-example')
这会把该元素固定在距离页面顶部 200 像素的位置。但如果场景是我们需要把元素固定在左侧而不是顶部又该怎么办呢?这时使用动态参数就可以非常方便地根据每个组件实例来进行更新。
<div id="dynamicexample"> <h3>Scroll down inside this section ↓</h3> <p v-pin:[direction]="200">I am pinned onto the page at 200px to the left.</p> </div>
const app = Vue.createApp({ data() { return { direction: 'right' } } }) app.directive('pin', { mounted(el, binding) { el.style.position = 'fixed' // binding.arg 是我们传递给指令的参数 const s = binding.arg || 'top' el.style[s] = binding.value + 'px' } }) app.mount('#dynamic-arguments-example')
基本用法就这些,更多简写什么的看文档即可:
https://v3.cn.vuejs.org/guide/custom-directive.html
本文来自博客园,作者:咸瑜,转载请注明原文链接:https://www.cnblogs.com/bi-hu/p/16073642.html