目录
一、定义语法
1.局部指令:
new Vue({
directives:{指令名:配置对象或回调函数}
})
2.全局指令:
vue.directive(指令名,配置对象或回调函数)
二、配置对象中常用的3个回调
bind:指令与元素成功绑定时调用
inserted:指令所在元素被插入页面时调用
update:指令所在模板结构被重新解析时调用
三、备注
指令定义时不加v-,使用时需要加v-
指令名如果是多个单词,要使用kebab-case命名的方式,不要用camelCase命名
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
<!-- 引入Vue -->
<script type="text/javascript" src="../js/vue.js"></script>
</head>
<body>
<!-- 准备好一个容器 -->
<div id="root">
<h2>欢迎和{{name}}一起学习</h2><hr>
<h3>a的值是{{a}}</h3>
<input type="text" v-fbind="a"><br><br>
<button @click="a++">点我让a+1</button>
</div>
</body>
<script type="text/javascript">
Vue.config.productionTip = false // 阻止 vue 在启动时生成生产提示
//定义全局指令
Vue.directive('fbind',{
// 在指令与元素成功绑定时调用
bind(element,binding){
element.value = binding.value
},
//指令所在元素被插入页面时调用
inserted(element,binding){
element.focus()
},
//指令所在模板被重新解析时调用
update(element,binding){
element.value = binding.value
}
})
new Vue({
el:'#root',
data:{
name:'才疏学浅的小缘同学',
a:0
}
})
</script>
</html>