文章目录
前言
如果我们需要直接访问组件中的底层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 {