- 全局指令
<body>
<div id="app">
<input type="text" v-focus>
</div>
<script>
Vue.directive('focus',{
inserted: function (el) {
el.focus();
}
})
new Vue({
el:"#app"
})
</script>
</body>
- 局部指令
<body>
<div id="app">
<input type="text" v-focus>
</div>
<script>
new Vue({
el:"#app",
directives: {
focus: {
inserted: function (el) {
el.focus();
}
}
}
})
</script>
</body>
- 常用钩子函数
-
函数
- bind: 绑定时候调用
- inserted: 插入到父节点时候调用
-
参数
- el: 元素,可以直接操作DOM
- binding: 对象
- name: 就是不包括v-后面的部分
- value: 就是双引号中的部分的真实值
- expression: 表达式就是双引号中的部分
- arg: 参数,就是:后边的部分
- modifiers: 修饰,就是点后面的部分
-
示例代码
- bind钩子函数
<body> <div id="app"> <p v-runoob:hello.a.b="message"></p> </div> <script> new Vue({ el:"#app", data:{ message:"fdsa" }, directives:{ runoob:{ bind: function (el,binding) { el.innerHTML = 'name:' + binding.name + '<br/>' + 'arg:' + binding.arg + '<br/>' + 'modifiers:' + JSON.stringify(binding.modifiers) + '<br/>' + 'expression:' + binding.expression + '<br/>' + 'value:' + binding.value; } } } }) </script> </body>- 简写形式
<body> <div id="app"> <p v-runoob:hello.a.b="message"></p> </div> <script> Vue.directive('runoob',function (el, binding) { el.innerHTML = 'name:' + binding.name + '<br/>' + 'arg:' + binding.arg + '<br/>' + 'modifiers:' + JSON.stringify(binding.modifiers) + '<br/>' + 'expression:' + binding.expression + '<br/>' + 'value:' + binding.value; }) new Vue({ el:"#app", data:{ message:"fdsa" } }) </script> </body>
-
- 钩子函数的值可以是任意的合法的js的表达式
<body>
<div id="app">
<p v-runoob="{ color: 'green', text: '菜鸟教程!' }"></p>
</div>
<script>
Vue.directive('runoob',function (el, binding) {
el.innerHTML = 'color:' + binding.value.color + '<br/>' +
'text:' + binding.value.text;
})
new Vue({
el:"#app"
})
</script>
</body>