代码示例
可以通过ref变量实现绑定$ref,或者getCurrentInstance来获取$refs
/**
* $ref 使用方式,变量名和组件的属性ref值一致
*/
const hChildRef = ref()
console.log(hChildRef, "hChildRef")
const instance = getCurrentInstance()
// const self=(instance as ComponentInternalInstance).proxy as ComponentPublicInstance
const self = instance?.proxy
console.log(self, "this_proxy")
console.log(self?.$refs, "this_instance_refs_24234")
onMounted(() => {
//在onMounted 里面调用$ref才能获取到dom对象
console.log(self?.$refs, "this_instance_refs")
console.log(self?.$refs?.hChildRef, "this_instance_refs_hChildRef")
/**
* hChildRef.value 返回一个Proxy对象,可以获取子组件defineExpose暴露的数据
*/
console.log(hChildRef.value, "hChildRef_value")
// hChildRef.value.onMounted(() => {
// console.log("hChildRef_onMounted")
// })
})
// 直接变量divRef 和ref属性同名即可获取$refs
const divRef = ref()
onMounted(() => {
//需要放在mounted这样才能保证dom已加载
divRef.value.addEventListener("click", () => {
console.log("click")
}, false)
const { proxy } = getCurrentInstance() as ComponentInternalInstance
//通过?可以解决提示问题,如果不加? 则会提示错误,但是不影响运行
//as HTMLElement 才能调用element方法,不会提示错误
(proxy?.$refs?.divRefTwo as HTMLElement).addEventListener("click", () => {
console.log("click_divRefTwo")
}, false)
/**
* 下面方式不影响运行,但是会提示错误,所以规划做法还是 as HTMLElement 类型断言
proxy?.$refs?.divRefTwo?.addEventListener("click", () => {
console.log("click_divRefTwo2")
}, false)
*/
})
const divRefThree = ref()
//这里会报错,因为dom还没渲染
/**
divRefThree.value.addEventListener("click",()=>{
console.log("click_divRefThree")
})
*/
onMounted(() => {
console.log(divRefThree.value, "divRefThree_value")
divRefThree.value.addEventListener("click", () => {
console.log("click_divRefThree")
})
})
- html
<template>
<div class="greetings">
<h1 class="green">{{ msg }}</h1>
<h3>
You’ve successfully created a project with
<a href="https://vitejs.dev/" target="_blank" rel="noopener">Vite</a> +
<a href="https://vuejs.org/" target="_blank" rel="noopener">Vue 3</a>.
</h3>
<div>{{ abd }}</div>
<div>fatherInject:{{ fatherInject }}</div>
<hChild ref="hChildRef" />
<div style="color:blue" @click="changePage">change_page</div>
<div style="color:blue" @click="changePageParams">changePageParams</div>
<img style="width:30px;height:30px" :src="mypic" alt="">
<div ref="divRef">$ref</div>
<div ref="divRefTwo">$ref_instance</div>
<div ref="divRefThree">$ref_instance_three</div>
</div>
</template>
前端工程师、程序员