关于 vue3 模板引用

本文详细介绍了在Vue3中如何使用模板引用,包括在普通元素、v-for循环中以及组件上的应用。通过ref属性,可以直接访问DOM元素或组件实例。在选项式API中,可通过this.$refs访问,而在组合式API中,需要声明同名ref变量。在v-for中,字符串形式的ref会返回所有元素的数组,而函数形式的ref不推荐使用。对于子组件,父组件可以访问子组件实例,但若使用组合式API,需注意expose选项来暴露特定接口。
摘要由CSDN通过智能技术生成


前言

如果我们需要直接访问组件中的底层DOM元素,可使用vue提供特殊的ref属性来访问


1.访问模板引用

  1. 在视图元素中采用ref属性来设置需要访问的DOM元素
    a. 该ref属性可采用字符值的执行设置
    b. 该ref属性可采用v-bind:或:ref的形式来绑定函数,其函数的第一个参数则为该元素
  2. 如果元素的ref属性值采用的是字符串形式
    a. 在选项式 API JS中,可通过this.$refs来访问模板引用
    b. 在组合式 API JS中,我们需要声明一个同名的ref变量,来获得该模板的引用

访问模板引用【选项式】

<script>
export default {
   
    data: () => ({
   
        accountEl: null,
        passwordEl: null
    }),
    methods: {
   
        changeAccountInputStyle() {
   
            this.accountEl = this.$refs.account // 获取账号输入框的 DOM
            console.log(this.accountEl)
            this.accountEl.style = "padding: 15px"
            this.accountEl.className = "rounded"
            this.accountEl.focus()
        },
        passwordRef(el) {
    
            this.passwordEl = el  // el 元素是密码输入框
        },
        changePasswordInputStyle() {
   
            console.log(this.passwordEl) 
            console.log(this.$refs) // 函数式声明的 ref,不会在this.$refs中获取
            this.passwordEl.style = "padding: 15px"
            this.passwordEl.className = "rounded"
            this.passwordEl.focus()
        },
    }
}
</script>


<template>
    <!-- ref 字符串值形式 -->
   账号输入框:<input type="text" ref="account">
   <button @click="changeAccountInputStyle">改变账号输入框的样式</button>

   <hr>

   <!-- ref 函数形式:元素渲染后,会立即执行该函数 -->
   密码输入框:<input type="password" :ref="passwordRef">
   <button @click="changePasswordInputStyle">改变密码输入框的样式</button>
</template>

<style>
.rounded {
   
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

爱敲码的老余

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值