Vue自定义指令
不带参数的自定义指令
-
为何需要自定义指令?
内置指令不满足需求
-
自定义指令的语法规则(获取元素焦点)
Vue.directive('focus', { inserted: function(el){ // el 表示指令所绑定的元素 // 获取元素的焦点 el.focus(); } }); const app = new Vue({ el: "#app", data: {}, });
注意:Vue实例对象必须写在自定义指令之后,否则会报错
-
自定义指令用法
<div id="app"> <input type="text" v-focus /> <input type="text" /> </div>
带参数的自定义指令
-
改变元素背景颜色
Vue.directive('color', { inserted: function(el, binding){ // el 表示指令所绑定的元素 // console.log(binding.value.color); el.style.backgroundColor = binding.value.color; } }); const app = new Vue({ el: "#app", data: { msg: { color: "yellow" } }, });
-
指令的用法
<div id="app"> <input type="text" v-color="msg" /> </div>
局部指令
directives: {
"color": {
inserted: function(el, binding){
// el 表示指令所绑定的元素
// console.log(binding.value.color);
el.style.backgroundColor = binding.value.color;
}
}
}