Vue中的自定义指令

1.自定义指令

 自定义指令就是类似于v-on v-bind那样的指令,只不过是自己定义的

 2.局部自定义指令

const app = Vue.createApp({
     //局部指令需要注册后才能使用
      directives
      template: `
            <div>
             <input v-focus/>
            </div>
        `,
    });
    // 局部指令
    const directives = {
      focus: {
        // 组件挂载时让它focus
        mounted(el) {
          el.foucs();
        },
      },
    };

 3.全局自定义指令

 

 const app = Vue.createApp({
      template: `
            <div>
             <input v-focus/>
            </div>
        `,
    });
// 全局指令
    app.directive("focus", {
      beforeMount() {
        console.log("beforeMount");
      },
      beforeUpdate() {},
      updated() {},
      mounted(el) {
        el.focus();
      },
      beforeUnmount() {},
      unmounted() {},
});

 4.自定义指令传参

 


 <style>
      .header {
        position: absolute;
      }
 </style>

 const app = Vue.createApp({

     data:{
     return {

                left: 200
        }

     },
      template: `
            <div >
              //通过=指定参数,:后面指定的是参数名
              <div v-pos:left="left" class="header">
               <input/>  
              </div>
            </div>
        `,
    });


  app.directive("pos", {
   // 通过binding传过来参数
      mounted(el, binding) {
        el.style.top = binding.value + "px";
      },
      //   数据改变时也会执行
      updated(el, binding) {
        el.style.top = binding.value + "px";
      },
});

//也可以简写为下面的形式
app.directive("pos", (el, binding) => {
      el.style[binding.arg] = binding.value + "px";
    });

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值