VUE自定义指令
2023-06-04 本文已影响0人
小黄不头秃
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
</head>
<body>
<!-- 内置指令不满足需求
自定义指令的语法规则:
Vue.directive(
'focus' ,{
inserted:function(el){
el.focus();
}
}
)
自定义指令的用法:
<input type ="text" v-foucs>
-->
<!--
带参数的自定义指令(改变元素的背景颜色)
Vue.directive('color',{
bind:function(el,binding){
console.log(binding);
el.style.backgroundColor = binding.value.color;
}
});
-->
<!--
局部指令:如果想要注册局部指令,组件中也接受一个directives的选项,然后就可以在模板中的任何元素中使用新的v-focus指令
语法规则:
directives:{
focus:{
inserted:function(el){
el.fouces();
}
}
}
-->
<div id="app">
<input type="text" v-focus>
<input type="text" v-color="msg">
</div>
<script src="./vue/vue.js"></script>
<script>
// Vue.directive(
// 'focus' ,{
// // 钩子函数
// inserted:function(el){
// // 指令所绑定的元素
// el.focus();
// }
// }
// );
// Vue.directive('color',{
// bind:function(el,binding){
// console.log(binding);
// el.style.backgroundColor = binding.value.color;
// }
// });
var vm = new Vue({
el:"#app",
data:{
msg:{
color:"green"
}
},
methods:{},
directives:{
focus:{
inserted:function(el){
el.focus();
}
},
color:{
bind:function(el,binding){
console.log(binding.value);
el.style.backgroundColor = binding.value.color;
}
}
}
});
</script>
</body>
</html>