[Vue 3.4] App 中的 _instance 问题 #10824
Answered
by
liulinboyi
SnobbyVirus1973
asked this question in
Help/Questions
-
问题: 版本: |
Beta Was this translation helpful? Give feedback.
Answered by
liulinboyi
Apr 30, 2024
Replies: 1 comment
-
原因没有在子组件中 推荐用法父组件: <script setup>
import {
h,
ref,
createApp,
onMounted,
onBeforeUnmount
} from 'vue'
import Com from './Comp.vue'
const appRef = ref()
const handle = () => {
// instance是我在子组件Comp.vue中expose出去的
console.warn(appRef.value.instance)
}
onMounted(() => {
const demo = document.querySelector('#demo')
demo.addEventListener('click', handle)
const app = createApp({
render() {
return h(Com, { ref: appRef })
}
})
app.mount(demo)
})
onBeforeUnmount(() => {
const demo = document.querySelector('#demo')
demo.removeEventListener('click', handle)
})
</script>
<template>
<button @click="appRef.add">Add</button>
<div id="demo"></div>
</template>
<style scoped>
#demo {
font-size: 100px;
cursor: pointer;
}
</style> 子组件 Comp: <script setup>
import { ref, getCurrentInstance } from 'vue'
const count = ref(10)
defineExpose({
add() {
count.value++
},
instance: getCurrentInstance()
})
</script>
<template>
<div>
{{ count }}
</div>
</template>
|
Beta Was this translation helpful? Give feedback.
0 replies
Answer selected by
SnobbyVirus1973
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
原因
没有在子组件中
defineExpose
instance
属性,所以你在父组件通过ref
访问不到。推荐用法
在线例子
父组件: