vue2注册指令
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
<script src="vue.js"></script>
<style>
[v-cloak]{
display: none;
}
</style>
</head>
<body>
<div id="demo">
<p ref="content">hello world</p>
<button @click="hint">提示</button>
<p v-cloak>{{msg}}</p>
</div>
<div id="test1">
<p v-upper-text=msg1></p>
<p v-lower-text=msg1></p>
</div>
<div id="test2">
<p v-upper-text=msg2></p>
<p v-lower-text=msg2></p>
</div>
<script>
new Vue({
el:"#demo",
data:{
msg:"shit"
},
methods: {
hint(){
alert(this.$refs.content.innerHTML)
}
},
})
Vue.directive('upper-text',function(el,binding){
console.log(el,binding)
el.textContent=binding.value.toUpperCase()
})
new Vue({
el:"#test1",
data:{
msg1:"What The Tell With U"
},
directives:{
'lower-text':function(el,binding)
{
el.textContent=binding.value.toLowerCase()
}
}
})
new Vue({
el:"#test2",
data:{
msg2:"What Is Your PornHub"
}
})
</script>
</body>
</html>
vue3注册指令
<div id="app">
<input v-focus />
</div>
<script>
const { createApp } = Vue
const app = Vue.createApp({})
app.directive('focus', {
mounted(el) {
el.focus()
}
})
app.mount('#app')
</script>
参考