vue3 template refs dom的引用、组件的引用、获取子组件的值
介绍
通过 ref() 还可以引用页面上的元素或组件。
DOM 的引用
<template>
<div>
<h3 ref="h3Ref">TemplateRefOne</h3>
</div>
</template>
<script>
import { ref, onMounted } from '@vue/composition-api'
export default {
setup() {
// 创建一个 DOM 引用
const h3Ref = ref(null)
// 在 DOM 首次加载完毕之后,才能获取到元素的引用
onMounted(() => {
// 为 dom 元素设置字体颜色
// h3Ref.value 是原生DOM对象
h3Ref.value.style.color = 'red'
})
// 把创建的引用 return 出去
return {
h3Ref
}
}
}
</script>
组件的引用
父组件获取子组件的值
父组件 templateRefOne.vue
<template>
<div>
<h3>TemplateRefOne</h3>
<!-- 4. 点击按钮展示子组件的 count 值 -->
<button @click="showNumber">获取TemplateRefTwo中的count值</button>
<hr />
<!-- 3. 为组件添加 ref 引用 -->
<TemplateRefTwo ref="comRef" />
</div>
</template>
<script>
import { ref } from '@vue/composition-api'
import TemplateRefTwo from './TemplateRefTwo'
export default {
setup() {
// 1. 创建一个组件的 ref 引用
const comRef = ref(null)
// 5. 展示子组件中 count 的值
const showNumber = () => {
console.log(comRef.value.count)
}
// 2. 把创建的引用 return 出去
return {
comRef,
showNumber
}
},
components: {
TemplateRefTwo
}
}
</script>
子组件 templateRefTwo.vue
<template>
<div>
<h5>TemplateRefTwo --- {{count}}</h5>
<!-- 3. 点击按钮,让 count 值自增 +1 -->
<button @click="count+=1">+1</button>
</div>
</template>
<script>
import { ref } from '@vue/composition-api'
export default {
setup() {
// 1. 定义响应式的数据
const count = ref(0)
// 2. 把响应式数据 return 给 Template 使用
return {
count
}
}
}
</script>
script setup
如果使用 script setup 语法糖,应该使用 defineExpose
/**
* Vue `<script setup>` compiler macro for declaring a component's exposed
* instance properties when it is accessed by a parent component via template
* refs.
*
* `<script setup>` components are closed by default - i.e. varaibles inside
* the `<script setup>` scope is not exposed to parent unless explicitly exposed
* via `defineExpose`.
*
* This is only usable inside `<script setup>`, is compiled away in the
* output and should **not** be actually called at runtime.
*/
export declare function defineExpose(exposed?: Record<string, any>): void;
本文作者:guangzan
本文链接:https://www.cnblogs.com/guangzan/p/11838402.html
版权声明:本作品采用知识共享署名-非商业性使用-禁止演绎 2.5 中国大陆许可协议进行许可。
分类:
标签:
,
,
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】凌霞软件回馈社区,博客园 & 1Panel & Halo 联合会员上线
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】博客园社区专享云产品让利特惠,阿里云新客6.5折上折
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步