FrontendDeveloper.in

Vue.js question detail

How to use composition API in Vue2.0?

Vue 2.0 does not have native support for the Composition API, but you can use it via the official plugin: @vue/composition-api.

Let's see the usage in step-by-step instructions,

  1. Install the Plugin
npm install @vue/composition-api
# or
yarn add @vue/composition-api
  1. Register the plugin in your main.js file,
import Vue from 'vue';
import VueCompositionAPI from '@vue/composition-api';

Vue.use(VueCompositionAPI);

new Vue({
render: h => h(App),
}).$mount('#app');
  1. Using Composition API in Components You can now use ref, reactive, computed, watch, onMounted, etc., in your Vue 2 components.

Example: Counter Component

<template>
<button @click="increment">Increment</button>
</template>

<script>
import { ref } from '@vue/composition-api';

export default {
setup() {
const count = ref(0);

const increment = () => {
count.value++;
};

return {
count,
increment,
};
},
};
</script>

Note:

  • The @vue/composition-api plugin is compatible with Vue 2.6+.
  • It does not include all Vue 3 features (e.g., <script setup>, Suspense, Fragments).
  • Great for gradual migration or using modern Vue patterns in Vue 2.
Back to all Vue.js questions
Get LinkedIn Premium at Rs 399