自定义指令directive
在Vue中除了像v-model 和 v-show这样的默认内置的指令外, Vue 也允许注册自定义指令。自定义指令用于对DOM 元素进行底层操作。
局部自定义指令
局部自定义指令类似局部组件,组件使用directives进行引用,以输入框自动获得焦点为例。
// 注册一个局部自定义指令 v-focus
,并写入钩子mounted,mounted接收绑定元素el。
const directives = {
focus:{
mounted(el){
el.focus();
}
}
}
组件引用局部自定义指令,并使用自定义指令 v-focus
const app = Vue.createApp({
directives: directives,
template:`<input v-focus/>`
});
页面效果:
完整代码:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>vue自定义指令</title>
<!-- 使用CDN引入Vue -->
<script src="https://unpkg.com/vue@next"></script>
</head>
<body>
<div id="root"></div>
<script>
const directives = {
focus:{
mounted(el){
el.focus();
}
}
}
const app = Vue.createApp({
directives: directives,
template:`<input v-focus/>`
});
const vm = app.mount('#root');