目录
父子组件交互能力
ref引用组件
- ref是vue的一种reactive值
- 代表的是一个引用
- 例如:引用某个数值、对象......
- 例如:引用某个组件
- Coding
import { defineComponent, ref, watch } from "vue"
export const ExposeExamplese01 = defineComponent({
setup() {
const ipt = ref<HTMLInputElement | null>(null)
watch(ipt, () => {
if (ipt.value) {
ipt.value.value = "hello"
ipt.value.focus()
}
})
return () => {
return <input ref={ipt} />
}
}
})
expose暴露方法
import { defineComponent, ref, watch } from "vue"
export const ExposeExamplese02 = defineComponent({
setup() {
const someRef = ref<any>(null)
watch(someRef, () => {
if (someRef.value) {
// console.log(someRef.value) // A <div>A组件</div>
console.log(someRef.value) // B Proxy {…}
console.log(someRef.value.div) // B <div>B组件</div>
}
})
return () => {
// return <A ref={someRef} />
return <B ref={someRef} />
}
}
})
const A = () => {
return <div>A组件</div>
}
const B = defineComponent({
setup(props, { expose }) {
const divRef = ref<HTMLDivElement | null>(null)
expose({
foo: "bar",
text() {
console.log('text me!')
},
div: divRef
})
return () => {
return <div ref={divRef}>B组件</div>
}
}
})