文章目录
前言
如果我们需要直接访问组件中的底层DOM元素,可使用vue提供特殊的ref属性来访问
1.访问模板引用
- 在视图元素中采用ref属性来设置需要访问的DOM元素
a. 该ref属性可采用字符值的执行设置
b. 该ref属性可采用v-bind:或:ref的形式来绑定函数,其函数的第一个参数则为该元素 - 如果元素的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 {
border-radius: 15px

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

被折叠的 条评论
为什么被折叠?



