网站空间就是主机吗,白城市网站建设,网站开发中如何设计验证码,知舟网站建设除了 Vue 内置的一系列指令 (比如 v-model 或 v-show) 之外#xff0c;Vue 还允许你注册自定义的指令 (Custom Directives) 选项式API_自定义指令
templateh3自定义指令/h3p v-author文本信息/p
/template
script
e…除了 Vue 内置的一系列指令 (比如 v-model 或 v-show) 之外Vue 还允许你注册自定义的指令 (Custom Directives) 选项式API_自定义指令
templateh3自定义指令/h3p v-author文本信息/p
/template
script
export default {directives:{author:{mounted(element){element.innerHTML element.innerHTML -itbaizhan}}}
}
/script
组合式API_自定义指令
templateh3自定义指令/h3p v-author文本信息/p
/template
script setup
const vAuthor {mounted:(element) {element.innerHTML element.innerHTML -itbaizhan}
}
/script
全局与局部自定义指令
自定义指令是区分全局和局部注册在全局注册可以在任意组件中使用局部注册只在当前组件中使用
局部自定义指令
templateh3自定义指令/h3p v-blue蓝色效果/p
/template
script
export default {directives:{blue:{mounted(element){element.style.color blue}}}
}
/script
全局自定义指令
import { createApp } from vue
import App from ./App.vueconst app createApp(App)app.directive(red,{mounted(element){element.style.color red}
})app.mount(#app)
自定义指令钩子函数
自定义指令有很多钩子函数我们可以理解为是自定义指令的生命周期函数在不同的情况下会自动调用 钩子函数
templateh3自定义指令/h3p v-red v-ifflag{{ message }}/pbutton clickupdateHandler修改数据/buttonbutton clickdelHandler删除元素/button
/template
script setup
import { ref } from vue
const message ref(红色效果)
const flag ref(true)
function updateHandler(){message.value 修改的红色效果
}
function delHandler(){flag.value false
}
const vRed {// 在绑定元素的 attribute 前// 或事件监听器应用前调用created(el, binding, vnode, prevVnode) {console.log(created);},// 在元素被插入到 DOM 前调用beforeMount(el, binding, vnode, prevVnode) {console.log(beforeMount);},// 在绑定元素的父组件// 及他自己的所有子节点都挂载完成后调用mounted(el, binding, vnode, prevVnode) {console.log(mounted);},// 绑定元素的父组件更新前调用beforeUpdate(el, binding, vnode, prevVnode) {console.log(beforeUpdate);},// 在绑定元素的父组件// 及他自己的所有子节点都更新后调用updated(el, binding, vnode, prevVnode) {console.log(updated);},// 绑定元素的父组件卸载前调用beforeUnmount(el, binding, vnode, prevVnode) {console.log(beforeUnmount);},// 绑定元素的父组件卸载后调用unmounted(el, binding, vnode, prevVnode) {console.log(unmounted);}
}
/script
自定义指令钩子函数参数
指令的钩子会传递以下几种参数
el指令绑定到的元素。这可以用于直接操作 DOM。
binding一个对象包含以下属性。
value传递给指令的值。例如在 v-my-directive“1 1” 中值是 2。 oldValue之前的值仅在 beforeUpdate 和 updated 中可用。无论值是否更改它都可用。 arg传递给指令的参数 (如果有的话)。例如在 v-my-directive:foo 中参数是 “foo”。 modifiers一个包含修饰符的对象 (如果有的话)。例如在 v-my-directive.foo.bar 中修饰符对象是 { foo: true, bar: true }。 instance使用该指令的组件实例。 dir指令的定义对象。 vnode代表绑定元素的底层 VNode。
prevNode之前的渲染中代表指令所绑定元素的 VNode。仅在 beforeUpdate 和 updated 钩子中可用。
模拟v-show指令
templateh3自定义指令/h3p v-myShowflag{{ message }}/pbutton clickupdateHandler显隐Toggle/button
/template
script setup
import { ref } from vue
const message ref(模拟v-show指令)
const flag ref(true)
function updateHandler(){flag.value flag.value true ? flag.valuefalse : flag.value true
}
const vMyShow {updated(el, binding) {binding.value true ? el.style.displayblock : el.style.displaynone}
}
/script