vue的指令的生命周期以及$refs的应用

<template>
    <div>
        <!-- 指令的生命周期 -->

        <input type="text"><br>
        <input type="text" v-focus ><br>
        <input type="text"><br>
    </div>
</template>

<script>
    export default {
        directives:{
         /*下面这个写法是语法糖的写法,其触发时间是dom元素创建和更新时
                     focus(el){
                         // focus藏在原型->原型->原型里有focus的方法
                         el.focus();
                     }
                 }
             }
          */
         /*DOM元素:先创建->设置各种属性->添加到页面
         比如创建按钮
         1.创建元素:const.btn=document.createElement("button")
         2.设置各种属性:比如btn.id='btn'
         3.添加到页面:比如box.appendChild(btn)
         */
           focus:{
               //自选生命周期,来触发函数
               inserted(el){
                   //insert:代表dom元素插入到页面显示
                   el.focus();
               }
           },
         }
        }
</script>

<style lang="scss" scoped>

</style>

在这里插入图片描述

<template>
    <div>
        <input type="text"><br>
        <input type="text"><br>
        <input type="text" ref="a"><br>
        <button @click="doFocus">获得焦点</button>
        <!-- 点击按钮让p标签颜色变红 -->
        <p ref="b">hello</p>
    </div>
</template>

<script>
    export default {
        /* 需求:点击按钮让第二个输入框获取焦点
        也就是点击按钮调用focus方法*/
        methods:{
            doFocus(){
                /*
                下面这个是原生dom的查询写法
                 const inp=document.querySelectorAll("input")[2];
                inp.focus();
                */
              //使用ref属性可以把变量绑定在dom元素上 变量存储在$refs    
               console.log("$ref:",this.$refs);
               this.$refs.a.focus()
               this.$refs.b.style.color="red"
            }
        },
        
    }
</script>

<style lang="scss" scoped>

</style>

在这里插入图片描述

<template>
    <div>
        <button @click="b">123</button>
        <!-- 点击按钮 改p标签的颜色 -->
        <p ref="a">456</p>
    </div>
</template>

<script>
    export default {
        methods:{
            b(){
                this.$refs.a.style.color="red"
            }
        }
    }
</script>

<style lang="scss" scoped>

</style>

在这里插入图片描述

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值