zoukankan      html  css  js  c++  java
  • Vue学习笔记【14】——自定义指令

    1.自定义全局和局部(私有)自定义指令

     // 自定义全局指令 v-focus,为绑定的元素自动获取焦点:
     ​
         Vue.directive('focus', {
     ​
           inserted: function (el) { // inserted 表示被绑定元素插入父节点时调用
     ​
             el.focus();
     ​
           }
     ​
         });
     ​
     ​
     ​
         // 自定义局部(私有)指令 v-color 和 v-font-weight,为绑定的元素设置指定的字体颜色 和 字体粗细:
     ​
           directives: {
     ​
             color: { // 为元素设置指定的字体颜色
     ​
               bind(el, binding) {
     ​
                 el.style.color = binding.value;
     ​
               }
     ​
             },
     ​
             'font-weight': function (el, binding2) { // 自定义指令的简写形式,等同于定义了 bind 和 update 两个钩子函数
     ​
               el.style.fontWeight = binding2.value;
     ​
             }
     ​
           } ​

    2.自定义指令的使用方式

    <input type="text" v-model="searchName" v-focus v-color="'red'" v-font-weight="900">
    

    3.Vue 1.x 中 自定义元素指令【已废弃,了解即可】

     Vue.elementDirective('red-color', {
       bind: function () {
         this.el.style.color = 'red';
       }
     });

    使用方式:

    <red-color>1232</red-color>

    4.函数简写

    在很多时候,你可能想在 bindupdate 时触发相同行为,而不关心其它的钩子。比如这样写:

     Vue.directive('color-swatch', function (el, binding) {
       el.style.backgroundColor = binding.value
     })
    

      

     

  • 相关阅读:
    MySQL启动报错Starting MySQL. ERROR! The server quit without updating PID file
    vue安装
    web漏洞分析防御
    dedecms三级目录
    阿里云Linux服务器漏洞修复
    Windows下elasticsearch安装并且同步数据库
    解决ecshop清除缓存css样式没反应问题
    PHP正则匹配替换图片地址
    阿里云漏洞修复
    Apache Pig
  • 原文地址:https://www.cnblogs.com/superjishere/p/11909739.html
Copyright © 2011-2022 走看看