What is the process for updating the parent file's data value from the sub file in vue.js?

I have a new project in Vue.js where I need to update the data value of app.vue based on the checkbox status in the child component. The code snippets for both files are as follows:

Component File:


<template>
   <div>
    <h3>Edit User</h3>
    <p>Local: {{ $route.query.local }}</p>
    <p>Number: {{ $route.query.q }}</p>
    <label><input type="checkbox" @click="change()">Customize</label>
   </div>
</template>

<script>
   export default {
      props:["changeParentStatus"],
      data() {
        return {
          active: false
        };
      },
      methods: {
        change() {
          this.active = !this.active;
          console.log(this.active);
          this.changeParentStatus(this.active);
        }
     }
  }
</script>

App.vue File:


<template>
  <div :class="[{ 'active': active }]">
   <div class="row">
     <div class="col-xs-12 col-sm-8 col-sm-offset-2 col-md-6 col-md-offset-3">
      <h1>Routing</h1>
      <hr>
      <app-header></app-header>
      <router-view :changeParentStatus="changeStatus"></router-view>
    </div>
  </div>
 </div>
</template>

<script>
  import AppHeader from "./components/Header.vue";
  export default {
   data(){
     return{
       active: true
     }
   },
   methods:{
      changeStatus(active){
         this.active=active
      }
   },
   components:{
      appHeader: AppHeader
   }
 }
</script>

<style>
 .active{
   background: black;
 }
</style>

I'm looking for a way to toggle the value of the 'active' data property in app.vue between true and false based on the checkbox state in the component file. Any assistance would be greatly appreciated.

Folder Structure:

 
src---> app.vue
         components---->users----->userEdit.vue (component file)

Answer №1

Passing a function as an attribute to the child component is possible.

<app-header :changeParentStatus="changeStatus"></app-header>

This function acts as a parent callback.

<script>
  import AppHeader from "./components/Header.vue";
  export default {
   data(){
     return{
       active: true
     }
   },
   methods:{
       changeStatus(active){
           this.active=active
       }
   },
   components:{
      appHeader: AppHeader
   }
  }
 </script>

You can now call "changeParentStatus" within the child change function.

<script>
   export default{
    props:["changeParentStatus"],
    methods:{
       change() {
            this.active = !this.active
            console.log(this.active)
            this.changeParentStatus(this.active);
        }

    }
   }
 </script>

Answer №2

It appears that you are looking to transfer the checkbox value from a child component to its parent. To achieve this, create an event in the parent component and emit that event from the child component.

In the parent component, handle the event as follows:

<router-view @changeParentStatus="changeStatus"></router-view>

The changeStatus is an event/method defined using v-on (or @ shorthand).

Then, emit the event from the child component:

<label>
    <input type="checkbox" 
       @click="$emit('changeParentStatus', $event.target.checked)">
 customizer</label>

For more information, visit: Vue.JS Guide

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

Creating real-time chat using Node.js

I am looking to create a live chat feature using node js. Can someone provide guidance on how to achieve this? Here are the use cases I have determined: Users will have the option to click on a link or icon labeled 'Online chat support' on the ...

What strategies should I implement to effectively handle a substantial amount of input to my RSS endpoint?

Currently, I have a dynamic web application built using Angular and ASP.Net WebAPI. The process involves sending a JSON query to an API endpoint and receiving the response in RSS format. $scope.generateRss = function(query){ $http.post("api/url", quer ...

Vuetify recognizes the data; however, it is not being displayed/rendered

I have a project that utilizes Vuetify and I need to display a table of "customer" information. Everything was functioning properly with Vuetify 1.5, but now I am required to upgrade to the latest version, which is 2.0. The issue I'm encountering is ...

Place the child atop the stacked blocks

I need the .square div to always remain at the top, creating a visual effect where it appears as if the following section with its own .square is sliding up and the .square halts precisely at the position of the previous section's square. The code sn ...

clicking on a DIV element

I am trying to trigger a JavaScript function by clicking on a DIV element, but for some reason it is not working as expected. I have gone through various examples provided by the helpful people here, but still can't figure out what I'm doing wron ...

Tips for creating a permission dialog for posting messages on a wall

I have developed a Facebook application using the Facebook JavaScript SDK and Android PhoneGap. I am able to post messages to the Facebook wall, but now I want to include a permission dialog before posting the message. The goal is to only allow the message ...

Automatically hiding divs when clicked using HTML and CSS

Apologies if this question has been asked before, but I have two onclick divs and I'm trying to achieve a specific behavior. When I open the first one, I want it to automatically close when I open the second one, and vice versa. Below is the HTML cod ...

Upon clicking close, the icons do not appear as expected

Currently, I am developing an application using Next.js. In this application, there is a functionality where clicking on the hamburger icon in mobile mode hides the icons of a Slide, and upon closing the hamburger, they should reappear. The overall struct ...

Tips for narrowing the width of a v-switch

Is there a way to reduce the clickable area of the v-switch component in order to make it smaller than its default 100% width? Any suggestions would be greatly appreciated. Thank you! https://i.sstatic.net/PHtQw.png Clickable v-switch example can be found ...

Two selection options controlling filters. The first choice influences the data shown in the second filter

I've been struggling for hours to figure out how to build this functionality. My code seems to be getting close, but I'm having trouble passing my selection from the HTML back to the controller. Here's my Angular code: var Categories = Pa ...

Trouble arises from duplicating custom SCSS code while making modifications to SaaS variables in vue.config.js

My goal is to create a structure for overriding Vuetify variables values. However, I am facing an issue where the custom scss files with custom classes that I import end up being repeated multiple times - 92 times to be precise. I have successfully overri ...

CSS droplists are missing their scrollbars

const elements = document.querySelectorAll('.selectBtn'); const options = document.querySelectorAll('.option'); let zIndexValue = 1; elements.forEach(element => { element.addEventListener('click', event => { const ...

Implementing ReactJs content from one page to another using jQuery ajax

I have been developing an application and have created some views in React Js. I am now looking to load these views onto another page using jquery load. Is this possible? [Let's say leave.html contains the react code. Now, I want to load leave.html i ...

Retrieve all the documents that fall within the range of two specific entries in MongoDB

In my MongoDB collection, the _id property of objects is a string data type. My goal is to retrieve documents in a specific order by performing a .find() operation followed by a .sort(). Ideally, I want to limit the extraction to only the records that fal ...

Customize your Vuetify app with a stunning background image

Looking to enhance the appearance of my Vuetify (Vue components super set) project by adding an image pattern in the background. I attempted to achieve this with the following code: body { background: url("/images/background.png") no-repeat center ce ...

Using Vue.compile in Vue 3: A beginner's guide

Is there a way to utilize Vue.$compile for compiling functions in Vue 3 runtime? I have previously used this function in Vue 2, an example being: Vue.compile('<custom-component />'); ...

Implementing user authentication using Devise-jwt on Ruby On Rails for the backend and Vuejs for the frontend

Currently, my backend is built on Ruby on Rails and I am using Vue.js for the frontend. I am looking to implement a comprehensive user authentication system similar to what Devise gem offers in Ruby on Rails. Despite researching and experimenting, I am s ...

Using the ESNEXT, Gutenberg provides a way to incorporate repeater blocks that

If you're like me, trying to create your own custom Gutenberg repeater block with a text and link input field can be quite challenging. I've spent hours looking at ES5 examples like this and this, but still feel stuck. I'm reaching out for ...

Move the finished task to the end of the list

Seeking guidance on successfully moving a checked list item to the bottom of the list after it has been clicked. Currently, you are able to add an item to the to-do list, mark it with a strike-through and reduce its opacity to 0.5 (graying it out). The go ...

What is the reason behind the necessity of adding an extra slash when reloading the page and controller in AngularJS by using $location.path()?

In AngularJS, when you use $location.path() and pass the same URL as the current one, it does not reload the page and controller. However, if you add an extra slash at the end of the URL like this: $location.path('/currentURL/'); it forces a re ...