How do I call a function in setup() method?

I need to call a function from methods:{} in my setup() method without any event. I need to execute this function when the page loads. How would I do it?

Thank you in advance.

Methods from the options API are not available inside setup() because the component instance has not been created yet. You’ll need to define your method inside setup and run it inside onMounted.

Something like this:

	setup() {
		const myMethod = (value) => console.log(value);

		onMounted(() => {
			myMethod();
		});
        
		...
	},

1 Like

Thank you but my problem is that I need to find a way to pass the results to my template. I can’t define my function inside setup() because it seems like it doesn’t have the route params in setup method.

UPDATE:

I found a way to get the route params in the setup method:

Instead of import {useRouter} from "vue-router";

I do import {useRoute} from "vue-router";

I will mark your answer as a solution because it helped me somehow.

Thank you one again.

Try this:

<template>
	<div>{{ profile }}</div>
</template>

<script lang="ts">
import { defineComponent } from "vue";
import { useRoute } from "vue-router";
export default defineComponent({
	setup() {
		const route = useRoute();

		const getId = () => route.params.id; // 

		let profile = reactive({});

		const getProfile = async () => {
			let profileId = route.params.id;
			const r = await editData.data("/profile", profileId);
			profile = r.data;
		};

		onMounted(() => {
			getProfile();
		});

		return {
			profile, // this will be available in your template
		};
	},
});
</script>
2 Likes

I’m glad you figured it out

1 Like

Thank you…might look basic But I’m new to Ionic and Vue; useRouter and useRoute are very confusing…I know that they are on the documentation but it’s not always clear.