<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>8.1自定义指令——基本用法</title>
</head>
<body>
<div id="app">
<input type="text" v-focus />
<div v-test:msg.a.b="messages"></div>
<div v-test1="{msg:'hello',name:'Leo'}"></div>
</div>
<script src="/node_modules/vue/dist/vue.js"></script>
<script>
Vue.directive("focus", {
inserted(el) {
el.focus();
}
});
Vue.directive("test", {
bind(el, binding, vnode) {
var keys = [];
for (var i in vnode) {
keys.push(i);
};
console.log(keys);
el.innerHTML = "name:" + binding.name + "<br>" +
"value:" + binding.value + "<br>" +
"expression:" + binding.expression + "<br>" +
"argument:" + binding.arg + "<br>" +
"modifiers:" + JSON.stringify(binding.modifiers) + "<br>" +
"vnode keys:" + keys.join(",")
}
});
/*
1.el :指令所绑定的元素,可以用来直接操作DOM
2.binding :一个对象,包含以下属性
2.1.name :指令名,不包括v-前缀
2.3.value :指令的绑定值,例如v-my-directive="1+1",valu的值是2
2.4.oldValue :指令绑定的前一个值,仅在update和componentUpdated钩子中可用,无论值是否改变都可用
2.5.expression :绑定值的字符串形式,例如v-my-directive="1+1",expression的值是"1+1"
2.6.arg :传给指令的参数,例如v-my-directive:foo,arg的值是foo
2.7.modifiers :一个包含修饰符的对象,例如v-my-directive.foo.bar,修饰符对象modifiers的值是{foo:true,bar:true}
3.vnode :Vue编译生成的虚拟节点,在进阶篇中介绍
4.oldValue :上一个虚拟节点仅在update和componentUpdated钩子中可用
*/
Vue.directive("test1", {
bind(el, binding, vnode) {
console.log(binding.value);
console.log(binding.value.msg);
console.log(binding.value.name);
}
})
new Vue({
el: "#app",
data: {
messages: "some text"
}
})
</script>
</body>
</html>
网友评论