我正在参加「掘金·启航计划」
Vue有常用的v-show和v-if之外,它还允许用户注册自定义指令
今天就来讲讲directive方法
1.用法
创建一个自定义指令,用来通过固定布局将元素固定在页面上。我们可以创建一个自定义指令,它的值以像素为单位更新被固定元素的垂直位置
<template>
<div v-pin=200>hallow world</div>
</template>
在main.vue中
import { createApp} from 'vue'
import App from './App.vue'
var app = createApp(App)
app.directive('pin', {
mounted(el, binding) {
el.style.position = 'fixed'
el.style.top = binding.value + 'px'
}
})
app.mount('#app')
这会把该元素固定在距离页面顶部 200 像素的位置。
动态参数
使用动态参数就可以非常方便地根据每个组件实例来进行更新。
<template>
<div v-pin:[direction]="200">hello world</div>
</template>
<script setup>
const direction = "left";
</script>
app.directive('pin', {
mounted(el, binding) {
el.style.position = 'fixed'
// binding.arg 是我们传递给指令的参数
const s = binding.arg || 'top'
el.style[s]= binding.value + 'px'
}
})
修改绑定值
为了使其更具动态性,我们还可以允许修改绑定值。
<template>
<input type="range" min="0" max="600" v-model="direValue" />
<div v-pin:[direction]="direValue">Hellow World{{ direValue }}</div>
</template>
<script setup>
import { ref } from "@vue/reactivity";
const direction = "top";
const direValue = ref(290);
</script>
在mian.js中添加'updated'钩子
app.directive('pin', {
mounted(el, binding) {
el.style.position = 'fixed'
const s = binding.arg || 'top'
el.style[s] = binding.value + 'px'
},
updated(el, binding) {
const s = binding.arg || 'top'
el.style[s] = binding.value + 'px'
}
})
2.directive的钩子函数 一个指令定义对象可以提供如下几个钩子函数 (均为可选):
created:在绑定元素的 attribute 或事件监听器被应用之前调用。在指令需要附加在普通的v-on事件监听器调用前的事件监听器中时,这很有用。beforeMount:当指令第一次绑定到元素并且在挂载父组件之前调用。mounted:在绑定元素的父组件被挂载后调用。beforeUpdate:在更新包含组件的 VNode 之前调用。updated:在包含组件的 VNode 及其子组件的 VNode 更新后调用。beforeUnmount:在卸载绑定元素的父组件之前调用unmounted:当指令与元素解除绑定且父组件已卸载时,只调用一次。
欢迎大家评论解锁更多用法