VUE中$refs的基本用法
ref 有三种用法:1、ref 加在普通的元素上,用this.$refs.(ref值) 获取到的是dom元素2、ref 加在子组件上,用this. $refs.(ref值) 获取到的是组件实例,可以使用组件的所有方法。在使用方法的时候直接this.$refs.(ref值).方法() 就可以使用了。3、如何利用 v-for 和 ref 获取一组数组或者dom 节点应注意的坑:1、如果通过v...
ref 有三种用法:
1、ref 加在普通的元素上,用this.$refs.(ref值) 获取到的是dom元素
2、ref 加在子组件上,用this. $refs
.(ref值) 获取到的是组件实例,可以使用组件的所有方法。在使用方法的时候直接this.$refs.(ref值)
.方法() 就可以使用了。
3、如何利用 v-for 和 ref 获取一组数组或者dom 节点
应注意的坑:
1、如果通过v-for
遍历想加不同的ref时记得加 :号,即 :ref =某变量
;
这点和其他属性一样,如果是固定值就不需要加 :号,如果是变量记得加 :号。(加冒号的,说明后面的是一个变量或者表达 式;没加冒号的后面就是对应的字符串常量(String))
2、通过 :ref =某变量 添加ref(即加了:号)
,如果想获取该ref时需要加 [0],如this.$refs[refsArrayItem] [0];
如果不是:ref =某变量
的方式而是 ref =某字符串
时则不需要加,如this.$refs[refsArrayItem]
。
1、ref 需要在dom渲染完成后才会有,在使用的时候确保dom已经渲染完成。比如在生命周期 mounted(){} 钩子中调用,或者在 this.$nextTick(()=>{})
中调用。
2如果ref 是循环出来的,有多个重名,那么ref的值会是一个数组 ,此时要拿到单个的ref 只需要循环就可以了。
例子1:
添加ref属性
<div id="app">
<h1 ref="h1Ele">这是H1</h1>
<hello ref="ho"></hello>
<button @click="getref">获取H1元素</button> </div>
获取注册过 ref 的所有组件或元素
methods: {
getref() {
// 表示从 $refs对象 中, 获取 ref 属性值为: h1ele DOM元素或组件
console.log(this.$refs.h1Ele.innerText);
this.$refs.h1ele.style.color = 'red';// 修改html样式
console.log(this.$refs.ho.msg);// 获取组件数据
console.log(this.$refs.ho.test);// 获取组件的方法
}
}
例2 vue代码
<img class="get_verification"
src="http://localhost:4000/captcha"
alt="captcha"
@click="getCaptcha"
ref="captcha">
methods: {
getCaptcha () {
// this.$refs.captcha 直接获取到Dom元素
this.$refs.captcha.src = 'http://localhost:4000/captcha?time='+Date.now()
}
}
表单中的input重置就需要使用ref属性
点击重置按钮时 需要获取到改属性对象
this.$refs.loginForm.resetFields() //即可完成重置
点击登录时 需要判断 验证通过或者失败会返回 false true
this.$refs.loginForm.validate(valid=>{
console.log(valid);
})
更多推荐
所有评论(0)