乐闻世界logo
搜索文章和话题

How to call method in setup of vuejs3 app?

1个答案

1

In Vue.js 3, you can call methods within the application setup using various approaches, such as invoking methods in lifecycle hooks, directly in templates, or via reactive references. Here are some typical examples:

1. Calling Methods in Lifecycle Hooks

In Vue.js 3, you can use lifecycle hooks from the Composition API, such as onMounted or onCreated, to call methods. These hooks ensure that methods are automatically invoked at different stages of the component lifecycle.

javascript
import { onMounted, ref } from 'vue'; export default { setup() { const message = ref(''); const fetchMessage = () => { message.value = 'Hello, Vue 3!'; }; onMounted(() => { fetchMessage(); }); return { message }; } };

In this example, the fetchMessage method is invoked after the component is mounted, used to set the message.

2. Directly Calling Methods in Templates

You can also directly use methods in Vue templates, especially when responding to user events.

vue
<template> <button @click="sayHello">Say Hello</button> <p>{{ message }}</p> </template> <script> import { ref } from 'vue'; export default { setup() { const message = ref(''); const sayHello = () => { message.value = 'Hello, Vue 3!'; }; return { sayHello, message }; } }; </script>

In this example, when the user clicks the button, the sayHello method is invoked.

3. Calling Methods via Reactive References

In Vue.js 3, by using reactive references (e.g., with ref or reactive), you can more flexibly call methods in templates or JavaScript code.

javascript
import { ref, watch } from 'vue'; export default { setup() { const count = ref(0); const incrementCount = () => { count.value++; }; watch(count, (newValue, oldValue) => { console.log(`Count changed from ${oldValue} to ${newValue}`); }); return { count, incrementCount }; } };

In this example, the incrementCount method is used to increment the count value, and whenever count changes, the watch method outputs the current and previous values.

These are some common ways to call methods in Vue.js 3. Each approach has specific use cases, and you can choose the appropriate method based on your requirements.

2024年11月20日 22:13 回复

你的答案