Ways to change props in a Vue component

One of my goals is to develop a custom checkbox using Vue. The idea is to utilize two icons from fontawesome - one for a locked state and the other for an unlocked state. Essentially, I want the icon to be locked when the checkbox is checked, and unlocked when it is unchecked.

Below is the snippet of code I have been working on:

<template>
   <div>
      <i @click="statusChanged()" v-if="!checked" class="fas fa-lock-open lock"></i>
      <i @click="statusChanged()" v-if="checked" class="fas fa-lock lock"></i>
   </div>
</template>
<script lang="ts">
import Vue from 'vue';
import { Prop } from 'vue/types/options';
export default Vue.extend({
    props: {
        checked: {
        type: Boolean as Prop<boolean>,
    },
},
methods: {
    statusChanged() {
        this.checked = !this.checked;
    },
},
});

However, I keep encountering the following error:

Cannot assign to 'checked' because it is a constant or a read-only property

Do you have any suggestions on how to resolve this issue? Any help would be greatly appreciated.

Answer №1

Check out the prop.sync modifier. It's designed specifically for situations where you need to update the parent's value while passing it as a property to the child:
https://v2.vuejs.org/v2/guide/components-custom-events.html#sync-Modifier

Simply indicate that the prop can be synced:

<Checkbox :checked.sync="foo"></Checkbox>

To update the parent, emit an update:prop event from the child:

this.$emit('update:checked', !this.checked)

This should provide a foundation for your solution:
https://codesandbox.io/s/97rl86n64

Answer №2

Answer integrated into the question by original poster @Marek, shared by the community.

After encountering the issue, I successfully managed to find a solution that closely resembled the suggestion made by @TommyF here.

Below is the resolved solution:

<template>
<div>
    <i v-if="!checked" class="fas fa-lock-open lock" @click="statusChanged()"></i>
    <i v-if="checked" class="fas fa-lock lock" @click="statusChanged()"></i>
</div>
</template>
<script lang="ts">
import Vue from 'vue';
import { Prop } from 'vue/types/options';
export default Vue.extend({
    props: {
        checked: {
            type: Boolean as Prop<boolean>,
        },
    },
    model: {
        prop: 'checked',
        event: 'click',
    },
    methods: {
        statusChanged() {
            this.$emit('click', !this.checked);
        },
    },
});
</script>

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

There seems to be an issue with transitioning the React.js page

I'm currently working on managing the page with react-hook, react-router-dom, and redux. The login functionality has been implemented, and I've written the code to redirect to the main page upon successful login. To achieve this, I utilized hi ...

Cannot iterate over array using v-for - The property or method "dailyData" is not defined in the instance but referenced during rendering

I need help with displaying daily weather data in a table <tr :v-for="dailyData in weatherData.daily"> <td>{{ dailyData }}</td> </tr> The weatherData variable is a data property that contains the necessary information. ...

Service for language translation in Angular

I attempted to use an angular translation service to translate English words to Chinese using a key-value mapping approach, but unfortunately, I was unsuccessful. Does anyone have any suggestions? Here is the JSON mapping: "At most {{ number }} wrods ...

Arranging a list of objects with a designated starting value to remain at the forefront

Consider the array and variable shown below: array = ['complete','in_progress','planned']; value = 'planned'; The goal is to always sort the array starting with the 'value' variable, resulting in: array ...

Transform a string into a boolean value for a checkbox

When using v-model to show checked or unchecked checkboxes, the following code is being utilized: <template v-for="(item, index) in myFields"> <v-checkbox v-model="myArray[item.code]" :label="item.name" ...

Error: UserService (?) is missing parameters and cannot be resolved

Upon compiling my application, an error is appearing in the console: Uncaught Error: Can't resolve all parameters for UserService (?) Despite having @Injectable() present for the UserService, I am unsure where to troubleshoot further. import {Inj ...

Vue converts the "open" attribute to the value of "open" in every tag

Utilizing vue.js (v2.6.12) components within laravel blade templates. In my project, MathML is also being used where I require the open attribute of the <mfenced> tag to be customized. Below is an example of mathematical expression in MathML. <mat ...

react-router: The 'history' type is not found in the current context

Here is some code snippet from App.tsx: interface AppProps{ history: any } export default class App extends React.Component<AppProps,...> { public state = { target: this.props.history.push('/') }; private route() { if (! ...

Error: Could not find module: Unable to locate 'rxjs/add/observable/throw' in 'D:AngularhttpErrorHandlingExamplesrcapp'

I'm working on an Angular project to practice error handling, but I encountered an issue when trying to import the 'throw' module. The error message reads as follows: Error Message: "ERROR in ./src/app/employee.service.ts Module not found: E ...

Could you tell me the kind of theme used in Material-UI version 5?

I've decided to switch my project over to MUI version 5 and embrace the use of emotion CSS. It's come to my attention that I need to incorporate the theme property, but now TypeScript is prompting me for a type definition for it. The current code ...

Exploring the power of Async/Await with Angular 5 HttpClient and forEach

I am struggling to implement async/await in my code to show a spinner when I click on a button and hide it once I have all the data. Below is a simplified version of what I have: .ts: isLoading: boolean = false; onLoad() { this.isLoading = true; ...

Function that yields promise result

I need help figuring out how to make this recursive function return a promise value. I've attempted various approaches, but they all resulted in the search variable ending up as undefined. public search(message: Message) { let searchResult: strin ...

Checkbox will be automatically selected and the input box will be automatically populated when a value is detected

I have recently set up a sandbox for testing purposes: https://codesandbox.io/s/sweet-agnesi-qbf7g?file=/src/components/HelloWorld.vue Let's discuss a scenario where we have an array of objects like this: let sampleArrayOfObject = [{ Item: &qu ...

Managing the Vuetify select value: assigning to an array or object

Here are the codes I am using: <template> <v-col cols="12" sm="6" md="3" class="px-1 text_details_color3"> <v-select :items="items" :label="lang.category" ...

Transferring a variable from an Angular 2 constructor into the template via the then statement

I'm struggling with implementing a secure login system. My goal is to first check the device's native storage for an item named 'user', then verify if the user exists in our database, and finally retrieve the unique id associated with t ...

Is it possible for an Interface's property to be a type that contains an array?

As I dive into the Angular code, I encountered a peculiar type for a property within an Interface named 'Origin' that has left me perplexed. Here's the snippet: export interface Origin { areaNum?: number; open?: { [key: stri ...

The editor is locked and choices are displayed in a vertical orientation

I'm currently experimenting with using draft js in my project to create a wysiwyg editor. However, I've encountered an issue where the editor appears vertically instead of horizontally when I load the component. Any idea why this might be happen ...

Angular 2/Typescript experiencing a glitch with Jquery carousel functionality

After properly installing and importing jquery in my project, I encountered a specific issue. Within my application code, there is a line that reads as follows: $('#myCarousel').carousel("next"); Upon running npm start, an error is thrown: ...

Uh-oh! A circular dependency has been detected in the Dependency Injection for UserService. Let's untangle this web and fix the issue!

Encountering the following error: "ERROR Error: Uncaught (in promise): Error: NG0200: Circular dependency in DI detected for UserService." The auth.component.ts utilizes the UserService and User classes, while the user.service.ts only uses the User class. ...

Is it possible to customize webpack 4 modules in order to enable Jasmine to spy on their properties?

I've been facing issues trying to run my Jasmine test suite with webpack 4. Ever since I upgraded webpack, I keep getting this error message in almost every test: Error: <spyOn> : getField is not declared writable or has no setter The problem ...