Vue自定义指令
自定义指令总结: 1、 定义语法: 局部指令: new Vue(directives:{指令名:配置对象}或directives:{指令名:回调函数}) 全局指令: Vue.directive(指令名,配置对象) 或Vue.directive(指令名,回调函数) 2. 配置对象中三个回调: 1. bind: 指令与元素成功绑定时调用 2. inserted : 指令所在元素被插入页面时被调用 3. update: 指令所在模板被重新解析时调用 3. 备注 1. 指令定义时不加v- ,但使用时要加v- 2. 指令名如果是多个单词,要使用kebab-case 命名方式 不要用camelCase命名
代码实列
<body> <div id="root"> <div>n的值是<span v-text="n"></span></div><br> <div>放大十倍的n是 <span v-big="n"></span></div><br> <button @click="n++"> 点我n+1</button> <hr> <!-- 文本框一开始就获取焦点 --> <input type="text" v-fbind="n"> </div> <script> 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; }, }) // //全局定义自定义指令(函数式) Vue.directive("big", function (element, binding) { //将n扩大10倍,再填入标签中 element.innerText = binding.value * 10 }) new Vue({ el: "#root", data: { n: 1, }, //自定义指令(局部定义) // directives: { // // 函数式定义 // big(element, binding) { // //将n扩大10倍,再填入标签中 // element.innerText = binding.value * 10 // }, // 对象式定义 // fbind:{ // bind(element,binding){ // element.value = binding.value; // }, // inserted(element,binding){ // element.focus() // }, // update(element,binding) { // element.value = binding.value; // }, // } // } }) </script> </body>
· 阿里巴巴 QwQ-32B真的超越了 DeepSeek R-1吗?
· 10年+ .NET Coder 心语 ── 封装的思维:从隐藏、稳定开始理解其本质意义
· 【译】Visual Studio 中新的强大生产力特性
· 【设计模式】告别冗长if-else语句:使用策略模式优化代码结构
· 字符编码:从基础到乱码解决