ref 有三种用法:
1、ref 加在普通的元素上,用this.ref.name 获取到的是dom元素
<div id="app">
<div ref="testDom">11111</div>
<button @click="getTest">获取test节点</button>
</div>
this.$refs.p
2、ref 加在子组件上,用this.ref.name 获取到的是组件实例,可以使用组件的所有方法。
3、如何利用 v-for 和 ref 获取一组数组或者dom 节点
ref 被用来给元素或子组件应用信息,引用信息将会注册到父组件的$ref对象上,
如果在普通的dom元素上,引用指向的就是dom元素;
如果在子组件上,引用就是指向组件实例
this.$refs介绍
$refs 只是在组件宣染完才填充,而不是响应式的。不能再模板中做数据绑定。
他仅仅是一个直接操作子组件的应急方案,要避免在模板或计算属性使用$refs
this.$refs是一个对象,持有当前组件中注册过 ref特性的所有 DOM 元素和子组件实例
1、ref 需要在dom渲染完成后才会有,在使用的时候确保dom已经渲染完成。
比如在生命周期 mounted(){} 钩子中调用,
或者在 this.$nextTick(()=>{}) 中调用。
2、如果ref 是循环出来的,有多个重名,那么ref的值会是一个数组 ,此时要拿到单个的ref 只需要循环就可以了
子组件
<template>
<p>{{str}}</p>
</template>
<script>
export default{
data(){
str:'子组件'
}
},
methods:{
add(){
this.str = '你好'
}
}
</script>
父组件
<p @click = fuadd()>
<children ref= 'children '></children>
</p>
<script>
import children from'../children.vue'
export default{
components:{
children
},
data(){
return{
msg2:''
}
},
methods:{
fuadd(){
this.$refs.children 返回一个对象
this.$refs.children.add() 调用子组件的方法
this.$refs.children.str 读取子组件的值
this.$refs.children.textContent 读取子组件的内容
this.$nextTick(() => {
this.msg2 = this.$refs.children.innerHTML
})
this.msg3 = this.$refs.children.innerHTML
}
}
}
</script>
ref 使用在外面的组件上
<div id="ref-outside-component" v-on:click="consoleRef">
<component-father ref="outsideComponentRef">
</component-father>
<p>ref在外面的组件上</p>
</div>
//组件/
var refoutsidecomponentTem={
template:"<div class='childComp'><h5>我是子组件</h5></div>"
};
var refoutsidecomponent=new Vue({
el:"#ref-outside-component",
components:{
"component-father":refoutsidecomponentTem
},
methods:{
consoleRef:function () {
console.log(this); // #ref-outside-component vue实例
console.log(this.$refs.outsideComponentRef); // div.childComp vue实例,组件实例
}
}
});
ref 用到元素上
<div id="ref-outside-dom" v-on:click="consoleRef" >
<component-father>
</component-father>
<p ref="outsideDomRef">ref在外面的元素上</p>
</div>
var refoutsidedomTem={
template:"<div class='childComp'><h5>我是子组件</h5></div>"
};
var refoutsidedom=new Vue({
el:"#ref-outside-dom",
components:{
"component-father":refoutsidedomTem
},
methods:{
consoleRef:function () {
console.log(this); // #ref-outside-dom vue实例
console.log(this.$refs.outsideDomRef); // <p>标签dom元素 ref在外面的元素上</p>
}
}
});