局部自定义指令
局部自定义指令是以变量的形式定义,定义后,需要接收,然后才能使用
eg:
// 自定义指令的定义
const directives = {
自定义指令名: {
updated(el, binding) {
// 处理内容
}
}
}
// 自定义指令的接收
const app = Vue.createApp({
//、、、
// 局部自定义指令接收
directives: directives
// 自定义指令的使用
template: `
<div v-自定义指令名>你好波吉,我是卡克</div>
`
})
全局自定义指令
全局自定义指令定义后可以直接使用
app.directive('自定义指令名', {
// 内容
})
如果要将 data() 里面的数据传给 指令: v-自定义指令名=“data里字段名”
如果自定义指令里面有 mounted() 和 updated(),且两者里面的内容一样,可以合并一起写
代码示例:
<!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>自定义指令</title>
<script src="https://unpkg.com/vue@next"></script>
<style>
.hello {
position: absolute;
}
</style>
</head>
<body>
<div id="root"></div>
</body>
<script>
// 局部自定义指令
const directives = {
change2: {
updated(el, binding) {
el.style.top = binding.value + 'px'
el.style.color = 'pink'
el.style.fontSize = '25px'
}
}
}
const app = Vue.createApp({
data() {
return {
top: 150
}
},
// 局部自定义指令接收
directives: directives,
template: `
<div v-change2="top" class="hello">你好波吉,我是卡克</div>
`
})
// 全局自定义指令
app.directive('change', {
mounted(el, binding) {
el.style.top = binding.value + 'px'
},
updated(el, binding) {
el.style.top = binding.value + 'px'
el.style.color = 'pink'
el.style.fontSize = '25px'
}
})
// 如果自定义指令里面有 mounted() 和 updated(),且两者里面的内容一样,可合并大一起写:
app.directive('change1', (el, binding) => {
el.style.top = binding.value + 'px'
})
const vm = app.mount('#root')
</script>
</html>