我们在了解vue inserted钩子函数之前,先来了解一下vue的钩子函数。
钩子
钩子这事情需要相对的理解,直白点说,它也只是一些函数而已。但是把一些指定情况的函数组合成一个链条,就像描述一个动作的开始到结束的过程,亦或者是一个人的出生到死亡的过程。
钩子函数的作用就是记录这个过程中的一些重要的细化的动作。
只不过是一些特定状态下的函数。
自定义指令的钩子函数,及自定义指令的使用场景
(1) bind:只调用一次,指令第一次绑定到元素时调用
(2) inserted:被绑定元素插入父节点时调用
(3) update:所在组件的虚拟节点更新时调用
(4) componentUpdated:所在组件的虚拟节点及子虚拟节点全部更新后调用
(5) unbind:只调用一次,指令与元素解绑时调用
案例
调用指令
<input type="text" v-myinput>
钩子函数:
directives:{ “指令名”:{ inserted(当前节点){ //对节点操作 } } }
例:例举一个带参数的自定义指令
directives:{ myinput:{ bind(el, binding) { el.focus(); } } }
bind和inserted钩子函数的区别
<!DOCTYPE html> <html> <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> <script src="js/vue.js"></script> </head> <body> <div id="app"> <!-- // 使用自定义指令的时 用v-* --> <h2 v-color>{{msg}}</h2> <h2 v-color>好谷就业力</h2> </div> <div id="app2"> <h2 v-color>{{msg}}</h2> </div> </body> <script> /* bind和inserted区别: bind无父节点 inserted有父节点 */ //自定义指令 Vue.directive("color", { //定义的时候直接写名字就行 bind: function(el) { console.log(el.parentNode); //null 父节点不存在 el.style.color = "red"; }, inserted: function(el) { console.log(el.parentNode); //DOM元素 父节点存在 el.style.color = "red"; } }) //定义一个作用范围为app的实例对象 new Vue({ el: "#app", data: { msg: "好谷学堂" } }) //定义一个作用范围为app2的实例对象 new Vue({ el: "#app2", data: { msg: "好谷二哥" } }) </script> </html>
常见的钩子函数
<!DOCTYPE html> <html> <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> <script src="js/vue.js"></script> </head> <body> <div id="app"> <h2 v-color="oRed">{{msg}}</h2> <button @click="changeMsg()">修改msg</button> </div> </body> <script> //定义全局指令v-color Vue.directive("color", { //钩子函数bind--自定义指令 bind: function(el, args) { el.style.color = args.value; }, //钩子函数inserted--自定义指令 inserted: function(el) { console.log("inserted"); }, //钩子函数update--数据修改时执行 update: function(el) { console.log("修改数据时执行了update钩子函数"); }, //钩子函数componentUpdated--数据修改完执行 componentUpdated: function(el) { console.log("数据修改完执行了componentUpdated钩子函数"); }, //钩子函数unbind--只调用一次,指令与元素解绑时调用 unbind: function() { console.log("元素与指令解绑后调用unbind钩子函数"); } //销毁见下方↓ }); //实例化一个Vue对象 let vm = new Vue({ el: "#app", data: { msg: "八个", oRed: "red" }, methods: { changeMsg() { this.msg = "msg被修改了"; } } }) //销毁实例 //销毁后数据不能再修改 vm.$destroy(); </script> </html>
通过以上内容我们知道了vue inserted钩子函数。感谢您访问“我爱捣鼓(www.woaidaogu.com)”网站的内容,希望对大家有所帮助!引用本文内容时,请注明出处!谢谢合作!