一、通过ref获取dom元素
<template>
<div class="ref">
<h2>ref的使用</h2>
<p ref="refp">通过ref获取dom元素</p>
<button @click="ObtainDom">获取p标签的dom元素</button>
</div>
</template>
<script>
export default {
data() {
return {};
},
methods: {
ObtainDom() {
this.$refs.refp.style.color = "yellow";
},
},
};
</script>
<style lang="scss" scoped></style>
二、通过ref引用组件实例
1.先引入一个组件,通过ref命名
2.再通过ref使用组件中的方法等
<template>
<div class="app">
<h2>我是父组件</h2>
<!-- ref的使用 -->
<RefVue ref="myref"></RefVue>
</div>
</template>
<script>
import RefVue from "./components/RefVue.vue";
export default {
name: "App",
components: {
RefVue,
},
data() {
return {};
},
methods: {
addRef(){
//使用子组件中的add()方法
this.$refs.myref.add()
}
},
};
</script>
<style></style>
RefVue代码
<template>
<div class="ref">
<h2>ref的使用</h2>
<p ref="refp">通过ref获取dom元素</p>
<button @click="ObtainDom">获取p标签的dom元素</button>
<p>{{ count }}</p>
<button @click="add">++</button>
<hr />
</div>
</template>
<script>
export default {
data() {
return {
count: 0,
};
},
methods: {
ObtainDom() {
this.$refs.refp.style.color = "yellow";
},
add() {
this.count += 1;
},
},
};
</script>
<style lang="scss" scoped></style>
三、this.$nextTick(callback)的应用
<template>
<div class="ref">
<h2>ref的使用</h2>
<!-- $nsxtTick的应用 -->
<!-- 需求:点击按钮显示输入框并自动获得焦点,失去焦点输入框消失显示按钮 -->
<input
type="text"
v-if="inputOnoff"
ref="inputRef"
@blur="inputOnoff = false"
/>
<button v-else @click="showInput">显示输入框</button>
</div>
</template>
<script>
export default {
data() {
return {
inputOnoff: false,
};
},
methods: {
showInput() {
this.inputOnoff = true;
// 输入框显示的时候自动获得焦点
// 为什么不能放在update中,因为只要data中的数据发生变化就会执行update
//在失去焦点输入框消失时inputOnoff发生改变也会执行update,这样程序就会报错找不到inputRef这个元素
this.$nextTick(() => {
this.$refs.inputRef.focus();
});
},
},
};
</script>
<style lang="scss" scoped></style>