Home > database >  vue.js 3 .value.click is not a function
vue.js 3 .value.click is not a function

Time:07-12

    <template>
            <RecyclablesPopup ref="LVP" ></RecyclablesPopup>
    </template>

    <script setup>
    import RecyclablesPopup from "../components/popups/RecyclablesPopup";
    import { ref } from 'vue';
    const LVP = ref(null);

    // ... after mounted I have an event with a legacy component and onclick handler:
    eventClick: function(calEvent)
        {
            console.log(LVP.value);
            LVP.value.click();
        }
    </script>

At the end I get Uncaught TypeError: LVP.value.click is not a function after I clicked.

console.log returns me the proxy object as expected Proxy { <target>: Proxy, <handler>: {…} }

Why can't I call click()?

CodePudding user response:

the click function should be exposed by the child component in order be accessed by the parent component :

RecyclablesPopup component

<script setup>

function click(){
  //.......
}
defineExpose({
 click
})
</script>

for more details please check https://vuejs.org/guide/essentials/template-refs.html#ref-on-component

CodePudding user response:

If you are using script setup you can't access functions, variables, etc., defined inside the referenced component. To change that you have to use the defineExpose compiler macro inside RecyclablesPopup component - check more in documentation

//inside RecyclablesPopup
<script setup>
import { ref } from 'vue'

const click = () => {
    //do something
}

defineExpose({
    click,
})
</script>

CodePudding user response:

You need to execute the function on the onMounted lifecycle to guarantee that the component is mounted to the DOM, as the value before the component is mounted will be undefined.

onMounted(() => {
  eventClick()
})

For more resources

https://vuejs.org/api/composition-api-lifecycle.html#onmounted

  • Related