简体   繁体   中英

How to pass ref from parent to child component in template

I am using this component https://element.eleme.io/#/en-US/component/popover

Issue related to triggering element (it is used to calculate where is popover located)

For the triggering element, you can write it in two different ways: use the slot="reference" named slot, or use the v-popover directive and set it to Popover's ref.

Everything ok with default examples. But I am using transparent wrapper for el-popover component like so.

<script id="my-popover" type="x-template">
<el-popover
  ref="mypopover"
  transition="el-zoom-in-top"
  v-bind="$attrs"
  v-on="$listeners"
>
  <!-- Pass on all named slots -->
  <slot
    v-for="slot in Object.keys($slots)"
    :slot="slot"
    :name="slot"
  />
  <span> My popover </span>
</el-popover>
</script>

It works ok with slot="reference" named slot.

<my-popover 
    placement="bottom"
    title="Title"
    width="200"
    trigger="manual"
    v-model="visible"
>
    <el-button
        slot="reference" 
        @click="visible = !visible"
    >
        Click me
    </el-button>
</my-popover>

But due to complex layout I need to use v-popover directive. Got no luck with wrapped component.

<my-popover
    ref="popover"
    placement="right"
    title="Title2"
    width="200"
    trigger="manual"
    v-model="visible2"
>
</my-popover>
<el-button 
    v-popover:popover
    @click="visible2 = !visible2"
>
    Click me too
</el-button>

So I need somehow to pass in v-popover reference to ref="mypopover" from wrapped component. Ie pass ref to child directly in template.

I've tried v-popover:popover.$refs.mypopover but that doesn't work.

Related codepen https://codepen.io/anon/pen/rgRNZr

Click on button Click me too should show popup connected to that button.

The problem is that the ref you want is the one that is on the el-popover but you are using the ref that is set on the my-popover component instead of the one you want.

This is kind of a wierd thing since that component wants a ref but it will be annoying to get one from the component inside your component.

I would put the button and popup with a slot in the same component.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM