ref引用概念
- 辅助开发者
不依赖于jQuery的情况下
,获取DOM元素或者组件引用 - 每个vue的组件实例上,都包含一个$refs对象,里面存储着对应的DOM元素或者组件的引用,默认情况下 $ref指向一个空对象
利用ref获取标签的dom改变标签字体颜色
- ref不能重复
- this下挂在的$refs对象里面挂载的ref
<template>
<div>
<h1 ref="myH1">APP根组件</h1>
<button @click="showThis">打印this</button>
</div>
</template>
<script>
export default{
data(){
return{
}
},
methods: {
showThis(){
console.log(this.$refs.myH1);
// 改变字体样式
this.$refs.myH1.style.color = 'red'
}
}
}
</script>
ref引入组件改变组件内部数量值
- 通过ref拿到组件的实例对象的引用
- 调用resetCount方法或者直接重置count值都可以
- Left组件
<template>
<div>
<h3>这是left组件 ----- {{count}}</h3>
<button @click="count++">count值+1</button>
<button @click="count=0">重置count值</button>
</div>
</template>
<script>
export default{
data() {
return{
count:0
}
},
methods: {
}
}
</script>
<style>
</style>
- App根组件
<template>
<div>
<h1 ref="myH1">APP根组件</h1>
<button @click="resetCount">重置</button>
<!-- 引用Left组件 -->
<Left ref="left"></Left>
</div>
</template>
<script>
import Left from "@/components/Left.vue"
export default{
components:{
Left
},
data(){
return{
}
},
mounted() {
console.log(this.$refs);
},
methods: {
resetCount(){
this.$refs.left.count = 0
}
}
}
</script>
<style>
</style>
this.$nextTick(()=>{})应用场景
问题:如下代码使用ref获取input的节点信息时会报出未定义iptRef
因为在为isShow给定true时,dom渲染需要一定的时间,这时候去获取input的焦点可能会出现问题
解决:使用this.$nextTick等到dom渲染完毕之后再执行对应得操作
- 反思:最开始我想的是既然dom渲染未完成,我们直接使用v-show可不可以,
v-show是不会杀死dom只会隐藏dom
,结果虽然并未爆出未定义iptRef错误,但是并不能获取相应得input框得焦点
<template>
<div>
<h1 ref="myH1">APP根组件</h1>
<!-- 遇到的问题 -->
<input v-if="isShow" type="text" ref="iptRef"></input>
<button v-else @click="hh">展示按钮</button>
</div>
</template>
<script>
export default{
data(){
return{
isShow: false
}
},
mounted() {
console.log(this.$refs);
},
methods: {
hh(){
this.isShow = true
// 解决办法
this.$nextTick(()=>{
this.$refs.iptRef.focus();
})
// this.$refs.iptRef.focus(); 直接使用报错iptRef未定义
console.log(this.$refs.iptRef);
}
}
}
</script>