I want to create my own checkbox in Vue. I want to use two icons from fontawesome (lock and unlock). When my checkbox is checked then icon should be locked otherwise unlocked.
Here is my code:
<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;
},
},
});
I received an error:
Cannot assign to 'checked' because it is a constant or a read-only property
Can you help resolve this issue?
As long as you're updating a reactive property (props, computed props, and anything in data ), Vue knows to watch for when it changes. All we have to do is update count , and Vue detects this change. It then re-renders our app with the new value!
The best way to force Vue to re-render a component is to set a :key on the component. When you need the component to be re-rendered, you just change the value of the key and Vue will re-render the component.
To specify the type of prop you want to use in Vue, you will use an object instead of an array. You'll use the name of the property as the key of each property, and the type as the value. If the type of the data passed does not match the prop type, Vue sends an alert (in development mode) in the console with a warning.
Take a look at the prop.sync
modifier. It is made for exactly this kind of case where you want to update the parents value but pass it as a property to the child:
https://vuejs.org/v2/guide/components-custom-events.html#sync-Modifier
Basically you mark the prop as being sync
'able:<Checkbox :checked.sync="foo"></Checkbox>
And to update the parent you emit an update:prop
event from the child:this.$emit('update:checked', !this.checked)
This should get you started for your solution:
https://codesandbox.io/s/97rl86n64
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With