Issues with responsiveness and calculated attributes in Vue 3 using the Composition API

Within this menu, there are different items:

Item 1 (marked as number 1 in orange) with the path: http://localhost:8080/#/documents

Item 2 (marked as number 2 in orange) with the path: http://localhost:8080/#/documents/1

Item 3 (marked as number 3 in orange) with the path: http://localhost:8080/#/documents/2 https://i.sstatic.net/Xn8k5.png

Upon clicking on item 2, the combobox highlighted with a blue box should reset to a default value, filtering the items in the table accordingly as shown in the screenshot below:

https://i.sstatic.net/UVZBd.png

Therefore, when clicking on item 1, I should be able to filter the table values based on the selected filters. To achieve this, I have implemented the following methods and properties:

let route = useRoute();
let filter = computed({
            get: () => {
                console.log('get');
                return createFilter(route.params);
            },
            set: (newValue: any) => {
                console.log('set');
                route.params = newValue;
            },
        });

This method is triggered when we receive filter criteria from a child component.

function onEventFiltersForGrid(filters: any) {
            filter.value = filters;
        }

Here is the method I have created to generate the filters:

function createFilter(routeParams: any) {
            console.log(routeParams);
            if (routeParams.folderId === undefined || routeParams.folderId === '') {
                console.log('first if');
                return [filterCategoryFolderId, '<>', null];
            }
            else if (routeParams.id !== undefined && routeParams.id !== '' && routeParams.id !== isNaN) {
                console.log('second if');
                return [
                    [filterCategoryFolderId, '=', Number.parseInt(routeParams.folderId)],
                    'and',
                    [filterId, '=', Number.parseInt(routeParams.id)]
                ];
            }
            else {
                console.log('else');
                return [filterCategoryFolderId, '=', Number.parseInt(routeParams.folderId)];
            }
        }

The issue I am facing is that when I choose an item in the combo to create new filters for the table, I encounter the error message: Write operation failed: computed value is readonly.

https://i.sstatic.net/rWeh2.png

Below is the HTML code snippet:

<div>
    <document-list :filter="filter" :showFolder="true" :showCategory="true" :showType="true" :showSubType="true">
        <!-- Filters -->
        <filter-hierarchy @EventFiltersForGrid="onEventFiltersForGrid($event)" :archivedId="archivedId"></filter-hierarchy>
    </document-list>
</div>

Answer №1

The reason for the error message you're encountering is that by default, a computed property is a getter.

In the setup() function with a standalone computed property, they provide the following example: Check out this Example

const number = ref(5)
const multipliedNumber = computed({
  get: () => number.value * 2,
  set: (val) => {
    number.value = val / 2
  },
})

multipliedNumber.value = 10
console.log(number.value) // 5 
  • Where do you initialize the ref()?
  • To access the value of the ref, use .value

In the Options API, computed properties with getters and setters can be defined as follows:

let filter = computed({
            get() {
                console.log('get');
                return applyFilter(route.params);
            },
            set(newValue: any) {
                console.log('set');
                route.params = newValue;
            },
        });

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

Errors occur with Metro bundler while utilizing module-resolver

Recently, I completed a project using the expo typescript template that runs on both iOS and Android platforms, excluding web. To enhance my development process, I established path aliases in the tsconfig.json file as shown below: "paths": { "@models/ ...

Implementing Formik in React for automatic updates to a Material-UI TextField when blurred

Presently, I am developing a dynamic table where users can simultaneously modify multiple user details in bulk (Refer to the Image). The implementation involves utilizing Material-UI's <TextField/> component along with Formik for managing form s ...

Assigning initial value to a BehaviorSubject in an Angular application

I'm still getting the hang of Rxjs. How do I go about initializing the first value of a BehaviorSubject with data from a custom select box model? Here's what the model looks like: private mainRangeDate: any = {beginDate: {year: 2018, mon ...

Dynamically changing the date format within the item-text of v-autocomplete in Vuetify

My current v-autocomplete component is fetching an array of items from GrowthTasks.edges to display. <v-autocomplete label="Start Week" :items="GrowthTasks.edges" item-text="node.growthStartDate" item-value="node.grow ...

The namespace does not have any exported object named 'LocationState'

I encountered the following issue while attempting to execute my TypeScript application: Namespace '"C:/DevTools/git/motor.ui/node_modules/history/index"' has no exported member 'LocationState'. Here is a snippet from my pack ...

How can I turn off strict null checks in TypeScript when using ESLint?

ESLint keeps flagging my object as potentially null despite having an if statement to check for it. const user: User | null = getUser() if (user) { // if (user !== null) doesn't work either await user.updateProfile({ di ...

Error in NextJS with TypeScript when updating data in a useState variable

Recently, I started working with TypeScript, ReactJS, and NextJS, but I encountered a TypeScript error that I need help fixing. My current project involves using NextJS 14, server actions, and Prisma as the ORM for a university-related project. An issue ar ...

The CosmosClient's read() method will only return an object if both the ID and partition key value are provided

After setting up a CosmosDB instance and inserting a test object into the container products, with the partition key set to /price, I encountered an issue. The item added had the following properties: { "id": "1234", "name": "A DB product", "p ...

What is the method for placing a title in the initial column with the help of v-simple-table from Vuetify.js?

I am interested in using the v-simple-table UI component from Vuetify.js to create a table similar to the one shown below. https://i.sstatic.net/QNdpJ.png After creating the code in codesandbox and previewing the output, I noticed that the title is not a ...

Leverage Vue's ability to inject content from one component to another is a

I am currently customizing my admin dashboard (Core-UI) to suit my specific needs. Within this customization, I have an "aside" component where I aim to load MonitorAside.vue whenever the page switches to the Monitor section (done using vue-router). Here ...

The functionality of d3 transition is currently non-existent

I've encountered an issue with my D3 code. const hexagon = this.hexagonSVG.append('path') .attr('id', 'active') .attr('d', lineGenerator(<any>hexagonData)) .attr('stroke', 'url(#gradi ...

Using a Vuejs web component as an input element in a non-Vue web application: A step-by-step guide

After creating a web component with VueJs using VueCli3, the compiled output appears as follows: <script src="https://unpkg.com/vue"></script> <script src="./my-lib.js"></script> <my-lib></my-lib> This particular web ...

Navigating between routes in Vue: A guide to smooth transitions between related elements across different views

Is there a way to smoothly transition between elements defined in different views when changing routes, also known as "Shared transitions" or "Native-like transitions" across various page layouts? Here are a few examples: Shared Element Transitions in a ...

Using Typescript to inherit from several classes with constructors

I am trying to have my class extend multiple classes, but I haven't been able to find a clean solution. The examples I came across using TypeScript mixins did not include constructors. Here is what I am looking for: class Realm { private _realms: C ...

Trouble displaying data in Vue Laravel retrieved from method

I've been staring at this code for two days and I feel like I'm missing something obvious. The goal here is to display an array of data in a modal, but for some reason it's not populating correctly when using v-for. If you can spot where I w ...

Vue3 - Quasar q-tabs do not maintain values between them

I am facing an issue while designing a screen to submit a form in modal using vue3 and quasar. I have organized the form components by tabulating them, but when I switch tabs, the current selection disappears, showing the old value when I return. However, ...

Exploring the Use of ExpressJS Session with Typescript

In my experience with using TypeScript in ExpressJS, I have encountered several issues. One of them involves accessing data in the request and response parameters provided by third-party middleware like express-session. Here is the code snippet that has b ...

Issue with importing Bootstrap-vue components when importing an npm package locally

Maybe I'm overcomplicating things, but here's the issue I'm facing: When I publish my project (my-navigation) to the npm registry and then npm install it in another project (my-vue-app), everything works perfectly. However, if I try to npm ...

The switchMap function is sending back a single item

I'm having an issue with switching the observable using the switchMap operator: return this.db.list(`UserPlaces/${this.authData.auth.auth.currentUser.uid}`, { query: { orderByChild: 'deleted', equalTo: false } }) .ma ...

I require clarity on this befuddling syntax that feels like descending into

I came across this example in the official documentation at https://angular.io/guide/form-validation#custom-validators return (control: AbstractControl): {[key: string]: any} => { const forbidden = nameRe.test(control.value); return forbidden ...