如何从 vue 3 中的 slot 获取 ref?

Mr.*_* RJ 6 ref slot vuejs3

我需要将名称为test1 的ref 集中起来,设置一些值,该值放置在组件槽中(从外部)。有可能以某种方式做到这一点吗?我尝试从 $refs 或 $slots 获取,但失败了。

应用程序.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>
Run Code Online (Sandbox Code Playgroud)

组件.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>
Run Code Online (Sandbox Code Playgroud)

Pri*_*wen 4

您可以简单地通过事件或道具传递引用。这是使用您的示例的解决方案。

   <!-- App.vue -->
   <div id="app">
    <HelloWorld :test="inputEl">
      <template v-slot:input>
        <input type="text" ref="test1" />
      </template>
    </HelloWorld>
   </div>

    <script>
        export default {
          name: 'App',
          mounted() {
            this.inputEl = this.$refs.test1;
          },
          data() {
            return {
              inputEl: {}
            }
          }
        };
    </script>
   
   <!-- HelloWorld.vue -->
   <template>
     <slot></slot>
     <hr />
     <input type="text" ref="test2" />
   </template>
   
   <script>
    export default {
      name: 'HelloWorld',
      mounted() {
        this.$refs.test2.value = 'test 2 value';
        
        // Use the prop. Or watch it until it has been updated.
        this.props.test.value = "test 1 value";
      },
    };
   </script>
Run Code Online (Sandbox Code Playgroud)