Can Vue instances support private computed properties?

Vue is a versatile tool that I utilize for both service classes and components.

When it comes to reactive computeds, they prove to be incredibly beneficial. However, I often find myself wanting a clear way to differentiate between public interface computeds and those meant for internal calculations only within the service class.

In TypeScript, marking methods or properties as private is straightforward, but when it comes to defining computeds with get, I am unsure of the best approach.

Would something like this be the most effective solution, or is there a better alternative?

private get myComputed(): number {
  # ...
}

Answer №1

  • When utilizing the innovative javascript private operator #, it renders the attribute inaccessible at runtime by the template or through the use of refs.
  • The Typescript private keyword creates the illusion of privacy during build time and within the IDE, however, once compiled, the field remains accessible.

For computed values, there are a couple of approaches:

// supported in Typescript 4.3
get #myComputed () {
  return 'I am privately accessed at runtime'
}

private get myComputed () {
  return 'I am only private at compile time'
}

On a side note: for leveraging Vue reactivity with "services" and "helpers", consider using the @vue/composition-api package for Vue 2. This allows you to export composables (reactive variables, computeds, watchers...) without creating a full Vue component.

To create truly private computeds, refrain from exporting them from your composable:

export function useHelper () {
  const counter = ref(0)
  // Private computed property not visible to outside clients of the composable
  const hasReachedMax = computed(() => counter > 10))

  const increment = () => {
    if(hasReachedMax) { return }
    counter.value++
  }
  
  return { counter, increment }
}

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

Securing User Profiles in Firebase

I am currently working on a coding issue that involves the security of user profiles. While it doesn't involve sensitive information like payment details or personal data, it does pertain to the ownership of a profile. Currently, I store users' ...

Switching between various components based on conditions within the same route in Angular

My goal is to have 2 separate views, one for the homepage and another for authentication. I want to display the LoginComponent on the route '/' and the SignupComponent on the route '/signup' if the user is not logged in, otherwise rende ...

Emphasize x-axis heading in a Highcharts graph

In my Highcharts bar graph, I am looking for a way to dynamically highlight the x-axis label of a specific bar based on an external event trigger. This event is not a standard click interaction within the Highcharts graph. Currently, I have been able to r ...

Learn the process of sending a delete request to a REST API with Angular

Is there a way to effectively send a delete request to a REST API using Angular? I am attempting to send a delete request with an ID of 1 My current approach is as follows: this.http.delete(environment.apiUrl+"id="+1).subscribe(data => { }); The va ...

How can you make sure that a class property in TypeScript always matches the name of the class?

Click here for an example interface ICommandHandler<T> { type: string // how can we ensure that this equals T.name? handle(command: T): void; } interface ICommand {} class CreateTaskCommand implements ICommand{} class CreateTaskCommandHandler ...

Retrieving locale messages by accessing the app context from customized .js files

Currently, I am developing a Vue.js application with Nuxt.js in SSR mode. The project includes plugins such as axios and vue-i18n. nuxt.config.js : export default { mode: 'universal', // additional configurations modules: [ '@nuxt ...

What's the deal with that see-through navigation bar?

As I scroll down the page, the navigation bar sticks to the top and the content continues scrolling up behind it. It gives the effect that the navigation bar is transparent. Find the code at this link. <html lang="en> <head> <meta charset= ...

Retrieving the output of a parent computed method in VueJS, using a child component

I am facing difficulties in passing the dynamically changing value of a computed method to my child component. I am creating a button component with different save states, but the button always remains stuck on one state and does not update according to th ...

synchronize the exchange of information and events between two components

Just joined this platform and diving into Angular 7 coding, but already facing an issue. I've set up two components along with a service. The data is fetched by the service upon clicking a button in the searchbar component, and I aim to display it i ...

What is the proper way to manage redirecting with Passport.js in Nuxt SSR?

I am currently utilizing Nuxt SSR in conjunction with express session, and I am encountering a situation where I have a passport JS redirect on the server side /** * POST /signup * Create a new local account. */ exports.postSignup = (req, res, next) =& ...

Exploring Touch Interactions in Vue.js 2.0

Recently I started working with Vue 2.0 and encountered the need to incorporate swipe gestures into my project. After exploring the official plugin called vue-touch, I discovered that it does not currently support Vue 2.0. Can anyone recommend alternative ...

The Quasar q-form reset button fails to erase the data stored in the form

I'm currently working with quasar q-forms and I am trying to achieve a functionality where the 'Reset' button clears both the values and the validation. Unfortunately, this does not seem to be working as intended. Is there something that I m ...

Exploring the concept of union types and typeguards in TypeScript

I'm struggling with this code snippet: function test(): any[] | string { return [1,2] } let obj: any[] = test(); When I try to run it in vscode, I get the following error message: [ts] Type 'string | any[]' is not assignable to type & ...

The Hapi response fails to display JSON data in a nested tree format

Hey there! I've got this object with a specific structure. Here it is: interface FolderWithContent { uuid: string name: string; folders: Array<FolderWithContent>; files: Array<Files>; } Just a heads up, Files is an extens ...

Modifying the color of the error icon in Quasar's q-input component: a step-by-step guide

https://i.stack.imgur.com/4MN60.png Is it possible to modify the color of the '!' icon? ...

Invent a customizable receptacle for component

I am working on a component and I want to be able to change the tag name of the container for that component, like this: <my-component tagName="section"></my-component> so that it renders like this: <section>... my inner component tags ...

What is the best way to link y and x coordinates to an image in a Vue component?

Looking for assistance on how to move an image with mouse click. I have successfully configured x and y mouse movement, but unsure of how to connect these coordinates to the image. Any guidance would be greatly appreciated! Using VUE.JS ...

Which Index Type is the best fit for my assignment?

Color, by default, is a string that is set to primary. However, when used as an index in the Colors array, I encounter an issue where it is recognized as an any type. This happens because a string cannot be used as an index on type '{..etc}' The ...

Errors TS2585 and TS2304 encountered during compilation of TypeScript file using Axios

What steps should I take to fix the errors that arise when attempting to compile my TypeScript code using tsc index.ts? node_modules/axios/index.d.ts:75:3 - error TS1165: In an ambient context, a computed property name must reference an expression of lite ...

I am having trouble getting Angular 6 to work with lowdb

I am currently in the process of developing an Electron app with Angular 6, utilizing lowdb as a local database. This is all very new to me and I am learning through trial and error. However, I seem to be encountering difficulty resolving the following er ...