Search code examples
vuejs2vue-composition-api

Vue 2 with Composition API Reactive


For a legacy project we need to use vue 2. However we want to implement state by using @vue/composition-api for vue 2

But my only question is, how to use it with options api?

I have a proof of concept with a .js file

    import { reactive } from '@vue/composition-api';

    const state = reactive({
        counter : 0
    })

    export default{ state }

For setup it is easy:

    <template>
        <h1>hi
            <div>We still in it: {{ counter }}</div>
            <button @click="increment">+</button>
        </h1>
    </template>
    
    <script>
    import { defineComponent, computed } from '@vue/composition-api'
    
    export default defineComponent({
        name: "TestStateHello",
        setup() {
            const store = require("./useState").default;
    
            return {
                counter: computed(() => store.state.counter),
                increment: () => store.state.counter++,
            };
        },
    })
    </script>

But when i want to use regular options api to have access to reactive state of counter i don't seem to know how.

your help will be very grateful!


Solution

  • Just import it globally (outside of the returned options object):

    <template>
        <h1>hi
            <div>We still in it: {{ counter }}</div>
            <button @click="increment">+</button>
        </h1>
    </template>
    
    <script>
    import { defineComponent, computed } from '@vue/composition-api'
    // Alternative (after fixing export): import {store} from './useState';
    // You can use this in setup, too - no need to the require inside the setup()
    const store = require("./useState").default;
    
    export default defineComponent({
        name: "TestStateHello",
        computed: {
            counter: () => store.state.counter,
        },
        methods: {
            increment: () => store.state.counter++,
        }
    })
    </script>
    
    

    I suggest you change the export to:

    import { reactive } from '@vue/composition-api';
    
    const state = reactive({
        counter : 0
    })
    
    export state; // < then import works as above