【发布时间】:2022-06-29 12:52:37
【问题描述】:
我需要将名为 test1 的 ref 集中在一组放置在组件槽中的值(从外部)。有可能以某种方式做到吗?我尝试从 $refs 或 $slots 获取,但失败了。
App.vue
<template>
<div id="app">
<HelloWorld>
<input type="text" ref="test1" />
</HelloWorld>
</div>
</template>
```
<script>
import HelloWorld from './components/HelloWorld.vue';
export default {
name: 'App',
components: {
HelloWorld,
},
};
</script>
<style>
#app {
font-family: Avenir, Helvetica, Arial, sans-serif;
-webkit-font-smoothing: antialiased;
-moz-osx-font-smoothing: grayscale;
text-align: center;
color: #2c3e50;
margin-top: 60px;
}
</style>
Component.vue
===
<template>
<slot></slot>
<hr />
<input type="text" ref="test2" />
</template>
<script>
export default {
name: 'HelloWorld',
mounted() {
this.$refs.test2.value = 'test 2 value';
// how get ref 'test1' ?
},
};
</script>
【问题讨论】:
-
这似乎有点违反直觉,但我认为这个问题和我最近关于 vNode.componentInstance 的问题是相关的,一旦我们得到了一个答案,我们就会对两者都有答案。在这两种情况下,我们都试图获取通过插槽传入的组件的详细信息。 stackoverflow.com/questions/72399153/…