[Vuejs]-How to access `setup`'s inner state without exposing it via `data`?

3๐Ÿ‘

โœ…

You can expose your data to other components using expose method provided in setup,

// Foo.tsx
import { defineComponent, ref } from 'vue'

export default defineComponent({
  setup(props, { expose }) {
    // ๐Ÿ‘‡ how to access `number` outside the `Foo` Component?
    const number = ref(0)

    expose({
        number
    })

    return () => <div>{number.value}</div>
  },
})
๐Ÿ‘คAxel

1๐Ÿ‘

You could define a composable function called useLoader:

useLoader.ts:

import { ref } from 'vue'

const loading = ref(false)

export default function useLoader() {
  return {
    loading,
  }
}

then use it in Foo.tsx like:

import { defineComponent, getCurrentInstance } from 'vue'
import useLoader from './userLoader'

export default defineComponent({
  setup() {
    const { loading } = useLoader()

    return () => <div>{loading.value && <div> Loading ... </div>}</div>
  },
})

FooContainer.tsx

import Foo from '@/views/Foo'
import { defineComponent, onMounted, ref } from 'vue'
import useLoader from './userLoader'

export default defineComponent({
  setup() {
    const { loading } = useLoader()

    onMounted(() => console.log(loading.value))

    return () => <Foo />
  },
})

Leave a comment