【问题标题】:How get ref from slot in vue 3?如何从 vue 3 的插槽中获取 ref?
【发布时间】: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/…

标签: vuejs3 ref slot


【解决方案1】:

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

   <!-- App.vue -->
   <div id="app">
    <HelloWorld :test="$refs.test1">
      <template v-slot:input>
        <input type="text" ref="test1" />
      </template>
    </HelloWorld>
   </div>
   
   <!-- 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
        this.props.test.value = "test 1 value";
      },
    };
   </script>

【讨论】:

    【解决方案2】:

    在 Vue3 中,你可以使用函数 refs 和 scoped slot。

    // Parent
    const slotRef = ref()
    const setSlotRef = (el) => {
      slotRef.value = el;
    }
    
    <template>
      <slot name="child" :set-ref="setSlotRef">
    </template>
    
    // Child
    <template #child="{ setRef }">
       <button:ref="(el) => setRef(el)">
         button
       </button>
    </template>
    
    

    【讨论】:

      猜你喜欢
      • 2018-10-24
      • 2020-12-24
      • 1970-01-01
      • 2021-02-13
      • 2021-02-01
      • 2021-12-02
      • 1970-01-01
      • 2021-08-19
      • 1970-01-01
      相关资源
      最近更新 更多