What is the approach to accessing the internal state of `setup` without revealing it through `data`?

This query pertains to the return of render function in setup.

Let's consider a component called Foo:

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

export default defineComponent({
  setup() {
    // 👇 How can we access `number` outside the `Foo` Component?
    const number = ref(0)

    return () => <div>{number.value}</div>
  },
})

Is it necessary to use data to expose the variable number? For example:

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

export default defineComponent({
  data() {
    return {
      // 👇 Exposing `number` outside the component
      number: 0,
    }
  },
  setup() {
    return () => <div>{getCurrentInstance()?.data.number}</div>
  },
})

// FooContainer.tsx
import Foo from '@/views/Foo'
import { defineComponent, onMounted, ref } from 'vue'

export default defineComponent({
  setup() {
    const foo = ref<InstanceType<typeof Foo>>()
    //                          👇 Using `Foo`'s `number` in `FooContainer`
    onMounted(() => console.log(foo.value?.number))

    return () => <Foo ref={foo} />
  },
})

Any alternative methods to access the inner state variable number from Foo's setup without exposing it via data?

Answer â„–1

If you want other components to access your data, make use of the expose method within the setup function:

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

export default defineComponent({
  setup(props, { expose }) {
    // 👇 This is how you can expose the `count` variable outside the `Bar` Component.
    const count = ref(0)

    expose({
        count
    })

    return () => <div>{count.value}</div>
  },
})

Answer â„–2

To create a reusable function called useLoader:

Create a file named useLoader.ts:

import { ref } from 'vue'

const loading = ref(false)

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

Then, utilize it in the file Foo.tsx as follows:

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

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

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

In the file 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 />
  },
})

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Encountering an issue with utilizing the v-html directive within a Blade foreach loop triggers a Vue warning:

I'm attempting to utilize Vue's v-html within a blade foreach loop: @foreach($entries as $entry) <a href="/entry/{{$entry->id}}"><h3>{{ $entry->created_at->toRfc822String() }}</h3></a> <div v-html="< ...

Is it achievable to detect a hot-reload event in Vue 3?

Currently, I am implementing webpack hot-reload feature in my application built with Vue 3. While working on the project, I have noticed that whenever a reload occurs, the console displays multiple 'reload' messages. However, I am looking for a w ...

What is the best way to emphasize a selected row in a table when clicked using both Bootstrap 4 and Angular 6?

My Bootstrap table is styled with table-hover and all functions as expected. The .table-hover class activates a hover effect on table rows within a <tbody>. Additionally, I have implemented the following method: listClick(event, newValue) { this ...

Leaving out the return statement in an asynchronous typed function

Consider this example: export async function foo(): Promise<string>{ await bar() return; } No errors are thrown during compilation. However, if you change the code to: export async function foo(): Promise<string>{ await bar() } You w ...

Cypress terminal issue: Cannot find property in 'cy & CyEventEmitter' type

Tech stack: Angular v15 and Cypress V12 Despite successful runs of my component and end-to-end tests, I encounter peculiar terminal errors while running the tests. The issue could potentially stem from my Cypress configuration for shared commands. Here ...

Issues with Vue.js table component functionality

I have created a table where each tbody item is a component structured like this: <div class="panel"> <table class="table"> <thead> <tr> <th>Door</th> <th>Van</th> ...

API request was blocked due to the CORS policy

As I work on developing a web app using Vue.js, users must log in to receive an API key. My post request to the API through axios includes two parameters - a name and a password. However, upon form submission, persistent errors keep appearing: OPTIONS htt ...

Is there a simpler and more refined approach for handling Observables within RxJS pipelines?

Picture this: I have an observable that gives me chocolate cookies, but I only want to eat the ones without white chocolate. Since I am blind, I need to send them to a service to determine if they are white or not. However, I don't receive the answer ...

Trouble accessing nested components in Angular CLI beyond the first level of components

I'm diving into Angular CLI for the first time and trying to recreate a previous web project of mine. I've managed to nest and display components inside the root component successfully, but after that, I'm facing issues referencing any compo ...

Issue encountered after removing TypeScript 2.3 RC from Visual Studio

When attempting to compile a TypeScript project in Visual Studio, I encountered the following error message. Upon building, an issue arose with the task executable "tsc.exe." The error indicated a failure to load file or assembly 'System.IO.FileSyste ...

What is the best approach for determining which CSS file to import in next.js?

I'm currently facing the task of selecting which CSS file to apply in my next.js project. I have two separate CSS files, one for desktop and one for mobile devices. My current method of importing CSS files is as follows: // _app.tsx import ".. ...

Using Vue.js and Axios to retrieve data and store it in an array

I am currently developing a typeahead feature for my project. The typeahead component accepts an array list like ['Canada', 'USA', 'Mexico']. However, I now have an axios API available to fetch a list of countries, but I am un ...

Issues encountered with the v-model functionality in a Laravel and Vue.js integrated to-do list

Recently, I created a to-do list application using Laravel and Vue.js. The concept is simple: users can add categories and within each category, they can create a list of tasks or to-dos. However, I encountered a minor issue with the input fields - whateve ...

When implementing axios interceptors, there is a recurring issue of API calls getting stuck in a loop when encountering

My VueJs application is utilizing interceptors for refreshing tokens with axios. I have implemented logic using interceptors and store dispatch. However, when the token expires and I reload the page, an API post call is made indefinitely, resulting in a lo ...

Utilizing React.hydrate in conjunction with Vue: A Beginner's Guide

Wondering about a unique scenario here - I have a website built with Vue and now I aim to showcase a library I developed in React. In order to steer clear of server-side rendering (SSR), I can simply wrap ReactDOM.hydrate(ReactApp, document.getElementById( ...

Error TS2307: Module 'bluebird' not located

Currently, my focus is on developing an app using Ionic 2 and Angular 2 along with Typescript. To incorporate messaging into my app, I opted to utilize the library amqp-ts. The installation of the library through npm was successful with the following comma ...

What is the best way to isolate Vue.js code files from Laravel blade templates?

Currently, I am in the process of developing an application using Laravel 5.3 and Vue Js. The structure of my application is as follows: resource/view/layouts/plane.blade.php (serves as master.blade.php) resource/view/layouts/dashboard.blade.php (funct ...

Typescript: When using ts-node-dev, an error occurred while trying to import express due to an unexpected

I am embarking on a fresh project using Typescript and I intend to set up the node server with typescript utilizing express. There's a helpful tutorial that explains how to execute a Typescript file without going through the hassle of compiling files, ...

Instead of using `await asyncCall()`, try using `(await asyncCall())[0]`

After examining the Typescript code below, I'm curious to understand the rationale behind assigning myArray with (await asyncRPCCall())[0] instead of simply using await asyncRPCCall(). Why is the result placed inside () and why return only the first e ...

Combine the date and time into one variable

Is there a way to save the date and time fields in a variable with the format: 0000-00-00T00:00:00.000Z? component.html <mat-form-field appearance="outline" class="pr-sm-8" fxFlex="50"> <mat-label>Fecha Inicio ...