vue中的自定义指令以及模拟v-text、v-html、v-on

注册自定义指令的方式注册v-focus自动聚焦指令:<div id="app"> <input type="text" v-focus="msg"></div>1. 全局注册Vue.directive("focus", { // Vue会对html代码进行解析 // 解析之后,会将解析后的内容重...
摘要由CSDN通过智能技术生成

注册自定义指令的方式

注册v-focus自动聚焦指令:

<div id="app">

    <input type="text" v-focus="msg">

</div>

1. 全局注册

Vue.directive("focus", {
        // Vue会对html代码进行解析
        // 解析之后,会将解析后的内容重新渲染到页面中
        // inserted函数,就会在当前指令所在的元素,被插入到页面中的时候执行
        inserted: function (el) {
          // el 函数中接收的形参el,其实就是当前指令所在的元素

          el.focus()
          // console.log(el);
        }
      })

2. 局部注册

在创建Vue实例的时候,参数对象添加directives属性,在属性中注册指令即可!

全局注册所有的vue实例都能用

局部注册,只能在当前的vue实例中使用

const vm = new Vue({
        el: "#app",
        data: {
          msg: "<h1>hello world</h1>"
        },
        directives: {
          focus: {
            inserted(el){
              el.focus();
            }
          }
        }
      });

自定义指令的钩子函数:

 directives: {
          focus: {

            // 当vue要对当前指令所在的元素进行解析的时候执行
            bind(el){
              console.log("bind 钩子函数被执行了")
            },
            // 当当前指令所在的元素被插入到页面中的时候,会执行的函数
            inserted(el){
              console.log("
  • 2
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值