What is the best way to optimize reactive values using the Vue composition API?

Imagine I have a block of code like this...

const computedStyle = computed(() =>
  normalizeStyle([undefined, styleProp, undefined])
);
const computedClass = computed(() =>
  normalizeClass([
    "button",
    classProp,
    {
      "button--pressed": pressed.value,
      "button--enterheld": enterHeld.value,
      "button--long-pressed": longPressed.value,
    },
  ])
);

I want to restructure it into something similar to the following

export const useNormalizedStyles = ({
  style: styleProp,
  class: classProp,
  preClass,
  postClass,
  preStyle,
  postStyle,
}: NormalizedStylesProps): NormalizedStylesResult => {
  const computedStyle = computed(() =>
    normalizeStyle([preStyle, styleProp, postStyle])
  );
  const computedClass = computed(() =>
    normalizeClass([preClass, classProp, postClass])
  );
  return {
    style: computedStyle,
    class: computedClass,
  };
};

and then make the function call like so

const { style: computedStyle, class: computedClass } = useNormalizedStyles({
  style: styleProp,
  preClass: "button",
  class: classProp,
  postClass: {
    "button--pressed": pressed.value,
    "button--enterheld": enterHeld.value,
    "button--long-pressed": longPressed.value,
  },
});

However, after making these changes, the updates do not seem to take effect. Perhaps I am missing a reactive somewhere.

Answer №1

After some trial and error, I finally managed to make it work using the following solution:


const { style: computedStyle, class: computedClass } = useNormalizedStyles({
  style: styleProp,
  preClass: "button",
  class: classProp,
  postClass: reactive({
    "button--pressed": pressed,
    "button--enterheld": enterHeld,
    "button--long-pressed": longPressed,
  }),
});

It's important to remember that the reactive values should only include the refs and not .value

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

How can I ensure that TypeScript recognizes when I add a missing property back to an object in this scenario?

I recently came across an issue while using Typescript: Omit nested property and ended up encountering more complex errors. So my question remains - how can I replace multiple nested props on a TypeScript input in the convert function? P.S. On a side not ...

Dynamic Binding of Checkboxes in Vuex

I am encountering a problem with binding checkboxes using Vuex. Even though I am using v-model with a variable that has a getter and setter to set or get the value in the store, I keep getting incorrect data in the store. The issue arises when I click on a ...

What is the process for updating information in Vue.js?

I need assistance with displaying the updated data in a modal. When I trigger the testing(data) function through a click event, the data appears correctly within the function. However, the template does not update and still shows the previous data. How can ...

New behavior in Vue 3: defineEmits is causing issues with defineProps data

Currently, I am working with Vue 3 and TS 4.4. In one of my components, I am using defineProps to define prop types. However, when I try to add defineEmits, VS Code starts indicating that my props variable is not recognized in the component template. Below ...

"Navigate back to a previous page in Vue Router without having to

I am currently exploring the option of creating a back button in my Vue.js application using vue-router that mimics the behavior of the browser's native back button. The challenge I'm facing is that when using history mode for the router and tryi ...

Guide on integrating Mapbox GL Draw into an Angular 8 project

I'm currently working on an Angular 8 project that utilizes Webpack. My integration of Mapbox GL JS was successful, however, I am facing issues with importing Mabox GL Draw. Here are the versions I am using: "@angular/core": "8.2.14", "mapbox-gl": "^ ...

ReactJs Error: Unable to access property value because it is undefined (trying to read '0')

I am currently attempting to retrieve and display the key-value pairs in payload from my JSON data. If the key exists in the array countTargetOptions, I want to show it in a component. However, I am encountering an error message stating Uncaught TypeError ...

PrimeNG's p-table in Angular is not being recognized when using @ViewChild

Here is the code snippet I am referring to: import { DataTable } from 'primeng/primeng'; @Component({ moduleId: module.id, templateUrl: 'search.component.html' }) export class SearchComponent { @ViewChild(DataTable) pr ...

Angular 6 ActivatedRoute Parameters

I'm having trouble retrieving the data of each record using ActivatedRoute. I've been able to get the ID for each one, but I can't seem to access the other data. Any suggestions? Check out my stackblitz example: https://stackblitz.com/edit/ ...

Angular 6 - Use *ngIf to apply the readonly attribute to an input when a certain condition is met

In my current project, I am attempting to set a condition on an input field where if a variable equals 'view', then the readonly attribute should be added to the input. Here is the code snippet I am currently using: <input *ngIf="mode == &ap ...

The Vue3 web components were unable to apply inline styles because of Content Security Policy restrictions

I recently developed a web component with a .ce.vue extension following the guidelines outlined here: https://vuejs.org/guide/extras/web-components.html#building-custom-elements-with-vue. By doing so, my styles were automatically inlined within the shadow ...

The NestJS server encounters an unhandled exception leading to a server

As a newcomer to Nest.js and in the process of building a REST API server with typeorm, I have encountered an issue related to async functions. If I forget to include the await keyword while using an async function, it may result in an exception like &apos ...

Tips for conducting key down event testing on a material ui MenuList element utilizing react-testing-library

Looking to test the key down event on my MenuList component. Component: import MenuItem from '@material-ui/core/MenuItem'; import MenuList from '@material-ui/core/MenuList'; import * as React from 'react'; export default fu ...

Using TypeScript to apply a typed decorator function to a subclass

I've taken on the challenge of creating a node.js and MongoDB ORM library similar to "Entity Framework" using TypeScript. This library will allow users to define a Model class (e.g. Person) that extends a Base class. The class decorator will enhance ...

When the variable type is an interface, should generics be included in the implementation of the constructor?

Here is a code snippet for you to consider: //LINE 1 private result: Map<EventType<any>, number> = new HashMap<EventType<any>, number>(); //LINE 2 private result: Map<EventType<any>, number> = new HashMap(); When the ...

An instance of an object is being added instead of parameters

I'm having some trouble making a server call using promises. Whenever I try to add my parameters, they end up showing as 'object%20Object' Here's the code snippet for the call: import { Injectable } from '@angular/core'; imp ...

Passing an object as an argument for a POST request in axios may not yield the desired results

I'm experiencing an issue while attempting to send a post request in VUE.JS using axios. Within my data, I have the TEST object set up like this data () { return { test:{ name: 'foo', surname: 'bar' } }; }, Here is the method be ...

Implementing a global provider in Ionic 3

I have integrated a provider in my app that needs to stay active at all times while the application is running to monitor the network connection status. Following this guide, I included the class in my app.module.ts file to ensure it functions as a global ...

The issue appears to be a missing space before the function parentheses in the

I am just getting started with learning Vue.js. During my project setup, I encountered an issue related to the "Missing space before function parentheses" error message. Below are the details of the 3 errors that I came across: ✘ http://eslint.org/docs ...

Having trouble sending an email using nodejs and mailgun

Before accusing me of asking a duplicate question, I want to clarify that I have already searched for solutions and none of them worked for me. For example, I tried the solution provided in this link: Example of the domain name for mailgun before nodejs? ...