Vue.js 3.0 Tutorial
Vue.js 3.0 Component Advanced
Vue.js 3.0 Transitions & Animations
Vue.js 3.0 Reusable & Combinable
Vue.js 3.0 Advanced
Vue.js 3.0 Tools
Vue.js 3.0 Scale
Vue.js 3.0 Accessibility
Vue.js 3.0 Migrating from Vue2
Vue.js 3.0 Contribute Documentation
Vue.js 3.0 API References
Vue.js 3.0 Style Guide
The Composition API in Vue 3.0 is a new way to write and manage your Vue.js components. It provides a more flexible way to reuse and organize code in large Vue applications. The Composition API is introduced alongside the existing Options API, and it doesn't replace the latter. You can use both in the same application depending on what suits your needs better.
To use the Composition API, you'll use a setup method in your component, which serves as the entry point for the API. Below is a simple example of a Vue 3.0 application that uses the Composition API's setup
method.
Firstly, let's create a new Vue 3 project using the Vue CLI:
vue create my-project
Select Vue 3 when asked which version of Vue to use.
In your App.vue
file, you could create a component that displays a message, and the message can be changed by clicking a button.
<template> <div> <p>{{ message }}</p> <button @click="changeMessage">Change Message</button> </div> </template> <script> import { ref } from 'vue'; export default { setup() { const message = ref('Hello, Vue 3!'); const changeMessage = () => { message.value = 'Message changed!'; }; return { message, changeMessage }; }, }; </script>
In the setup
function, we've defined message
using the ref
function from vue
, which makes it a reactive variable. The changeMessage
function changes the message
when it's called.
These are returned from the setup function, which means they will be available in the template of this component.
Finally, run your Vue 3 application:
npm run serve
Now, if you open the page in your browser, you'll see the message "Hello, Vue 3!". Clicking the button changes it to "Message changed!".
This is a simple example of how to use the Composition API's setup method in Vue 3.0. It provides a way to manage and organize your component's logic in a more flexible manner.
Vue 3.0 Composition API Installation Steps:
@vue/composition-api
package.npm install @vue/composition-api
Initializing Composition API in Vue 3.0:
main.js
).// main.js import { createApp } from 'vue'; import VueCompositionAPI from '@vue/composition-api'; import App from './App.vue'; const app = createApp(App); app.use(VueCompositionAPI); app.mount('#app');
Getting Started with Vue 3.0 Composition API Setup:
<!-- MyComponent.vue --> <template> <div>{{ message }}</div> </template> <script> import { ref } from '@vue/composition-api'; export default { setup() { const message = ref('Hello, Vue 3.0 Composition API!'); return { message, }; }, }; </script>