网站首页 > 博客文章 正文
利用ref函数获取组件中的标签元素,可以操作该标签身上的属性,还可以通过ref来取到子组件的数据,可以修改子组件的数据、调用子组件的方法等、非常方便. 适用于vue3.0版本语法,后续会讲到vue3.2版本setup语法糖有所不同。
语法示例:
<input标签 type="text" ref="inputRef">
<子组件 ref="childRef" />
const inputRef = ref<HTMLElement|null>(null)
const childRef = ref<HTMLElement|null>(null)
父组件代码:
<template>
<div style="font-size: 14px;">
<h2>测试ref获取普通标签 让输入框自动获取焦点</h2>
<input type="text" ref="inputRef">
<h2>测试ref获取子组件</h2>
<Child ref="childRef" />
</div>
</template>
<script lang="ts">
// vue3.0版本语法
import { defineComponent, ref, onMounted } from 'vue'
import Child from './child.vue'
export default defineComponent({
components: {
Child
},
setup() {
const inputRef = ref<HTMLElement|null>(null)
const childRef = ref<HTMLElement|null>(null)
onMounted(() => {
// ref获取元素: 利用ref函数获取组件中的标签元素
// 需求实现1: 让输入框自动获取焦点
inputRef.value && inputRef.value.focus()
// ref获取元素: 利用ref函数获取组件中的标签元素
// 需求实现2: 查看子组件的数据,修改子组件的某个值
console.log(childRef.value);
setTimeout(() => {
childRef.value.text = '3秒后修改子组件的text值'
}, 3000)
})
return {
inputRef,childRef
}
},
})
</script>
子组件代码:
<template>
<div>
<h3>{{ text }}</h3>
</div>
</template>
<script lang="ts">
// vue3.0版本语法
import { ref, defineComponent } from "vue";
export default defineComponent({
name: "Child",
setup() {
const text = ref('我是子组件');
return {
text
};
},
});
</script>
初始页面效果-输入框获取到了焦点,log打印出了子组件的所有数据:
初始3秒后页面效果,修改了子组件的text数据:
vue3.2版本语法:
<template>
<div style="font-size: 14px;">
<h2>测试ref获取普通标签 让输入框自动获取焦点</h2>
<input type="text" ref="inputRef">
<h2>测试ref获取子组件</h2>
<Child ref="childRef" />
</div>
</template>
<script lang="ts" setup>
// vue3.2版本语法
import { ref, onMounted } from 'vue'
import Child from './child.vue'
const inputRef = ref<HTMLElement|null>(null)
const childRef = ref<HTMLElement|null>(null)
onMounted(() => {
// ref获取元素: 利用ref函数获取组件中的标签元素
// 需求实现1: 让输入框自动获取焦点
inputRef.value && inputRef.value.focus()
// ref获取元素: 利用ref函数获取组件中的标签元素
// 需求实现2: 查看子组件的数据,修改子组件的某个值
console.log(childRef.value);
setTimeout(() => {
childRef.value.text = '3秒后修改子组件的text值'
}, 3000)
})
</script>
猜你喜欢
- 2025-06-08 vue3中使用ref函数代替响应式data
- 2025-06-08 Vue3开发极简入门(14):组件间通信之props、ref&defineExpose
你 发表评论:
欢迎- 最近发表
- 标签列表
-
- powershellfor (55)
- messagesource (56)
- aspose.pdf破解版 (56)
- promise.race (63)
- 2019cad序列号和密钥激活码 (62)
- window.performance (66)
- qt删除文件夹 (72)
- mysqlcaching_sha2_password (64)
- ubuntu升级gcc (58)
- nacos启动失败 (64)
- ssh-add (70)
- jwt漏洞 (58)
- macos14下载 (58)
- yarnnode (62)
- abstractqueuedsynchronizer (64)
- source~/.bashrc没有那个文件或目录 (65)
- springboot整合activiti工作流 (70)
- jmeter插件下载 (61)
- 抓包分析 (60)
- idea创建mavenweb项目 (65)
- vue回到顶部 (57)
- qcombobox样式表 (68)
- vue数组concat (56)
- tomcatundertow (58)
- pastemac (61)
本文暂时没有评论,来添加一个吧(●'◡'●)