Search code examples
vue.jsvuejs3vue-componentcomposable

How to print updated values of a composable in a vue-component


I am using vue3 with options API.As shown in the below posted code, in the class test.js should be a composable class. i want this class to reflect the change of state in another vue-component. in other words, the value of state changes as eminent in the code, i want to reflect the updated value of state in a vue-component. i want the vue-component to display the different states set in the test.js

to achieve that, i made the state of type ref as shown in the code.

in the vue-component as shonw below, i call and display the contents of state = useState() in ' state: {{state }}' and i expect the states to be displayed are not-satrted,started, processing and successful. But that does not happend.

how can i print updated values of state from test.js in a vue-component please.

vue-component:

<template>
    <span> state: {{state }}</span>
</template>

<script>
    import { useStates } from '../xx/xx/xxx/test.js';
    const state = useStates();
    

test.js

import { ref, onMounted, onUnmounted } from 'vue'

// by convention, composable function names start with "use"
export function useStates() {
  let state = ref('not-satrted')

  setTimeout(() => {
    state.value = 'started'
  }, 1000);

  setTimeout(() => {
    state.value = 'processing'
  }, 2000);

  setTimeout(() => {
    state.value = 'successful'
  }, 3000);
  // expose managed state as return value
  return state 
}

Solution

  • i figured it out. i did not add state to data object.it should be added to data object in the vue-component as follows:

    data() {
        return {
            state,
            ....
            ....
    },