源码
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8" />
<title>自定义指令</title>
<script type="text/javascript" src="../js/vue.js"></script>
</head>
<body>
<!--
需求1:定义一个v-big指令,和v-text功能类似,但会把绑定的数值放大10倍。
需求2:定义一个v-fbind指令,和v-bind功能类似,但可以让其所绑定的input元素默认获取焦点。
-->
<!-- 准备好一个容器-->
<div id="root">
<h2>{{name}}</h2>
<h2>当前的n值是:<span v-text="n"></span> </h2>
<!-- <h2>放大10倍后的n值是:<span v-big-number="n"></span> </h2> -->
<h2>放大10倍后的n值是:<span v-big="n"></span> </h2>
<button @click="n++">点我n+1</button>
<hr/>
<input type="text" v-fbind:value="n">
</div>
</body>
<script type="text/javascript">
Vue.config.productionTip = false
//定义全局指令
/* 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:'尚硅谷',
n:1
},
//自定义指令的配置项为 directives :
directives:{
//big函数何时会被调用?
// 1.指令 与 元素 成功绑定 时(一上来)。 //说的就是下面的fbind例子中的bind()。
// 2.指令 所在的模板 被重新解析 时。 //说的就是下面的fbind例子中的update()
/* 'big-number'(element,binding){
// console.log('big')
element.innerText = binding.value * 10
}, */
//定义指令 big
//原则: 不靠返回值
//element: 真实DOM元素(调用 big的元素本身)
//bingding: 绑定的是一个对象,我们关心的是对象中的 value属性值(也就是 v-big这个指令用到的属性值n)
big(element,binding){
//证明 element 是真实DOM元素: true
console.log(element instanceof HTMLElement) //应该是 true
console.log('big',this) //注意此处的this是window
// console.log('big')
//修改元素里面的内容:
element.innerText = binding.value * 10
},
/*
//先测试,引出问题: element.focus() 为什么不起作用。
fbind(element, binding){
element.value = binding.value
//一开始不会起作用。 因为 指令 与 元素 成功绑定 时,会调用一次 fbind() ,但是此时模板还没有显示出来(也就是此时还没有input),所以不会起作用。
element.focus()
}*/
//
fbind:{
/*
小结: 从下面可以看出 bind() 和 update() 往往相同的功能,所以在简写为 find(){}函数的时候,就相当于只写了 bing() update() 两个函数。
*/
//指令与元素成功绑定时(一上来),会调用 bind()
bind(element,binding){ //首次绑定时 1️⃣ 最先执行;
console.log('bind')
element.value = binding.value
},
//指令 所在元素 被插入页面 时,会调用 inserted()
inserted(element,binding){ //首次绑定时 2️⃣ 第二个执行;
console.log('inserted')
element.focus()
},
//指令 所在的模板 被重新解析 时,会调用 update()
update(element,binding){ //首次绑定时 ❌ 不会执行; //数据更新时, 1️⃣ 先执行 //update在数据变化时触发,早于 DOM 更新
console.log('update')
element.value = binding.value
},
componentUpdated(el, binding, vnode) { //数据更新时, 2️⃣ 后执行
console.log('componentUpdated')
}
}
}
})
</script>
</html>
