一、自定义指令绑值
实现输入框的样式距页面顶部指定像素
- 定义一个全局指令pos:binding变量可以接收元素传过来的值
app.directive('pos', {
mounted(el, binding) {
el.style.top = (binding.value + 'px')
}
})
- 元素使用自定义指令:
const app = Vue.createApp({
template: `
<div>
<div v-pos="400" class="header">
<input />
</div>
</div>
`
});
完整代码如下:
<!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>29</title>
<style>
.header {
position: absolute
}
</style>
<script src="https://unpkg.com/vue@next"></script>
</head>
<body>
<div id="root"></div>
<script>
// 自定义指令 directive
const app = Vue.createApp({
template: `
<div>
<div v-pos="400" class="header">
<input />
</div>
</div>
`
});
app.directive('pos', {
mounted(el, binding) {
el.style.top = (binding.value + 'px')
}
})
const vm = app.mount('#root')
</script>
</body>
</html>
- 也可以将数据放到data中:
const app = Vue.createApp({
data() {
return {
top: 100
}
},
template: `
<div>
<div v-pos="top" class="header">
<input />
</div>
</div>
`
});
注:
app.directive('pos', (el, binding) => {
el.style.top = (binding.value + 'px')
})
等价于:
app.directive('pos', {
mounted(el, binding) {
el.style.top = (binding.value + 'px')
},
updated(el, binding) {
el.style.top = (binding.value + 'px');
}
})