Vue.js - component's bound prop displays incorrect data

In my Vue.js app, I have a custom SwitchButton component that triggers a 'toggle' event when clicked. This event toggles the isEnabled property to true or false. However, I'm facing an issue when trying to set the initial value of isEnabled in the parent component.

Here is the code used in the parent component:

<SwitchButton v-model="distSwitch" :isEnabled="true">
    <label slot="left">{{ $t('general.dealer') }}</label>
    <label slot="right">{{ $t('general.wholesale') }}</label>
</SwitchButton>

Code for the SwitchButton component:

<template>
    <div class="switch-button-control">
        <div class="switch-button-label">
            <slot name="left"></slot>
        </div>
        <div class="switch-button" :class="{'enabled': isEnabled}" @click="toggle">
            <div class="button"></div>
        </div>
        <div class="switch-button-label">
            <slot name="right"></slot>
        </div>
    </div>
</template>

<script>
export default {
    name: 'SwitchButton',
    model: {
        prop: 'isEnabled',
        event: 'toggle'
    },
    props: {
        isEnabled: {
            type: Boolean,
            required: true
        }
    },
    methods: {
        toggle() {
            this.$emit("toggle", !this.isEnabled);
        }
    },
    created() {
        /*eslint-disable no-console*/
        console.log('isEnabled', this.isEnabled)
    }
}
</script>

Although I expect the console.log statement to output "isEnabled > true," it actually prints "false" instead. What am I missing here?

Answer №1

By setting the property isEnabled to a hard-coded value of true, any attempts to change it from the child component will not be effective.

A solution to this issue is to initialize a data variable in the parent component and use it as a property instead.

Here's an example template:

<SwitchButton v-model="distSwitch" :isEnabled="isEnabled" @toggle="toggleIsEnabled">
    <label slot="left">{{ $t('general.dealer') }}</label>
    <label slot="right">{{ $t('general.wholesale') }}</label>
</SwitchButton>

Declare the data like this:

data:()=>{
  return {
    isEnabled:true
  }
}

Add a method in the methods section:

toggleIsEnabled:function(value){
   this.isEnabled = value;
}

When the custom event emitter toggle in the SwitchButton component emits a value, it will trigger the callback function toggleIsEnabled in the parent component.

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

Exploring the execution of internal methods within an Angular service

My service is a simple one for Shoes app.factory('Shoes', function() { function x() {return 12;} function y() {return x();} return { x: x, y: y } }) I am trying to verify if the method x gets called when I invoke ...

Unable to access the POST value in the current context

I am having trouble retrieving the values from a simple form that consists of two files: APP.js and FORM.ejs. I am attempting to get the values submitted through the form. APP.js: const http = require('http'); const express = require("express"); ...

Callback function for Jeditable when the form is reset

My situation involves having a string with multiple lines separated by line breaks, which is then parsed into an <ul> hierarchy using JavaScript on the client side. The editing of this list is done using Jeditable, where the user sees the original te ...

Can we trust the accuracy of the official type definition for JSON.stringify?

Upon reviewing the official type definition for JSON.stringify, it appears that it states JSON.stringify always returns a string, even when passed undefined. interface JSON { stringify(value: any, /*...*/): undefined; } However, executing JSON.stringif ...

keeping the size consistent when submitting

I am currently developing a website that features several links on the side. When I click on one of these links, it redirects me to a specific .php file. Each PHP file contains the same header and footer. However, I have encountered an issue where every ti ...

Creating a seamless checkout experience: Setting up payment method for checkout sessions

In my app, I am utilizing the stripe payment integration for processing payments. I am currently setting up a session checkout for customers with the parameter mode=payment to facilitate receiving payments for orders. However, I am unsure of how to save th ...

Can anyone recommend a regular expression that would target values ranging from 0.5 to 24?

I'm searching for a regex pattern that can identify numbers within the range of 0.5 to 24, excluding cases like 0,5 or 22,5. The current pattern I'm using is: /^(([0-9]|1[0-9]|2[0-3])([^,])(\.(0|5)))$/ Despite having excluded the comma ,, ...

AngularJS self-invoking function

Encountering an issue with AngularJS. My HTML code looks like this: <tbody ng-repeat="show in pastShows"> <tr> <td><input value="{{show.address}}" type="text" id="addressUp" class="form-control" placeholder="address">&l ...

Comparing the benefits of expanding/collapsing all to focusing on individual items

Encountering an issue with expanding and collapsing a menu. The goal is to achieve two functionalities: First, to expand or collapse all items in the menu. The current implementation seems to be working correctly with the following code: $("#expandAll dt ...

Retrieve the downloaded status of a blob within a specific function

I need a way to verify if the blob downloading process is finished when generating an excel file on the NodeJS server side in response to a request from the React frontend side. Is there a method or promise that can help me achieve this? I want to update t ...

Consolidate a Node Typescript project into a single executable JavaScript file

Is it possible to consolidate a whole TypeScript project into a single executable js file? For instance, running node app.js where app.js is the compiled project. I've experimented with the compilerOption outFile, but haven't been able to gener ...

What causes JavaScript functions to return a NaN value?

While attempting to utilize an int value from a JSON file: { "buenos":274.0, "desaprobacion":0.13564668769716087, "malos":43.0, "proporcion":6.372093023255814 } within the app: var app = angular.module('angularSpa', ['ngRoute',&a ...

HTML anchor tag failing to redirect to specified link

I need to populate the URI property from an API result into an HTML format. I attempted to achieve this by calling a function and running a loop 3 times in order to display 3 links with the URI property of each object. However, the code is not functioning ...

Running a command line tool from a Node.js application: A step-by-step guide

My question pertains to running a command line tool from a node.js application, specifically one called tilemantle. In the documentation for tilemantle, it is suggested to install it globally and run it from the command line. However, I am interested in i ...

Removing an item from a JSON array based on its value using jQuery

This is a section of my JSON array: var videos = $j.parseJSON(' [ { "privacy":"public", "id":"1169341693" }, { "privacy":"private", "id":"803641223" }, { "privacy":"public", "id":"1300612600" }, ...... When I use co ...

Steps to successfully retrieve an image using JavaScript on the client side while circumventing any CORS errors

I have a React application where I am displaying an image (an SVG) and I want the user to be able to download it by clicking on a button. The image is stored in Firebase Storage. However, I am encountering an issue with CORS error: Access to fetch at &ap ...

Is there a way to change the color of a specific tab without affecting the content within it

I am attempting to change the color of an individual tab using jQuery. However, when I set the background attribute in CSS, it colors the entire background instead. What specific property should I be setting to only change the color of the tab itself? ...

Control the movement of the mouse pointer using javascript

For my University presentation on click-jacking, I came across an intriguing example that I wanted to replicate but didn't know where to start. The whole concept seemed very complex to me. To get a better idea, please take a look at this video: https ...

The JQuery function .load() is not functioning correctly

How can I dynamically load a webpage's content into a div using JavaScript and jQuery? Here's what I have tried: <script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js"></script> When a s ...

"Applying a background style to a button upon clicking, without any hover effects, in Vue

Clarification There is an icon within a button that, when clicked, triggers the opening of a menu. To ensure the menu is positioned correctly under the button, I have had to adjust the height. However, this adjustment has resulted in a background hover ef ...